Pandas 2.2 中文官方教程和指南(九·二)(2)https://developer.aliyun.com/article/1509700
现在比较以下内容:
In [143]: add_country_name(extract_city_name(df_p), country_name="US") Out[143]: city_and_code city_name city_and_country 0 Chicago, IL Chicago ChicagoUS
等同于:
In [144]: df_p.pipe(extract_city_name).pipe(add_country_name, country_name="US") Out[144]: city_and_code city_name city_and_country 0 Chicago, IL Chicago ChicagoUS
pandas 鼓励第二种风格,即称为方法链。pipe 可以轻松地在方法链中使用您自己或另一个库的函数,与 pandas 的方法并列使用。
在上面的示例中,函数 extract_city_name 和 add_country_name 分别预期将 DataFrame 作为第一个位置参数。如果您希望应用的函数将其数据作为,例如,第二个参数呢?在这种情况下,提供一个 (callable, data_keyword) 元组给 pipe。.pipe 将路由 DataFrame 到元组中指定的参数。
例如,我们可以使用 statsmodels 拟合回归。他们的 API 首先期望公式,然后是第二个参数 DataFrame,即 data。我们将函数、关键字对 (sm.ols, 'data') 传递给 pipe:
In [147]: import statsmodels.formula.api as sm In [148]: bb = pd.read_csv("data/baseball.csv", index_col="id") In [149]: ( .....: bb.query("h > 0") .....: .assign(ln_h=lambda df: np.log(df.h)) .....: .pipe((sm.ols, "data"), "hr ~ ln_h + year + g + C(lg)") .....: .fit() .....: .summary() .....: ) .....: Out[149]: <class 'statsmodels.iolib.summary.Summary'> """ OLS Regression Results ============================================================================== Dep. Variable: hr R-squared: 0.685 Model: OLS Adj. R-squared: 0.665 Method: Least Squares F-statistic: 34.28 Date: Tue, 22 Nov 2022 Prob (F-statistic): 3.48e-15 Time: 05:34:17 Log-Likelihood: -205.92 No. Observations: 68 AIC: 421.8 Df Residuals: 63 BIC: 432.9 Df Model: 4 Covariance Type: nonrobust =============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------- Intercept -8484.7720 4664.146 -1.819 0.074 -1.78e+04 835.780 C(lg)[T.NL] -2.2736 1.325 -1.716 0.091 -4.922 0.375 ln_h -1.3542 0.875 -1.547 0.127 -3.103 0.395 year 4.2277 2.324 1.819 0.074 -0.417 8.872 g 0.1841 0.029 6.258 0.000 0.125 0.243 ============================================================================== Omnibus: 10.875 Durbin-Watson: 1.999 Prob(Omnibus): 0.004 Jarque-Bera (JB): 17.298 Skew: 0.537 Prob(JB): 0.000175 Kurtosis: 5.225 Cond. No. 1.49e+07 ============================================================================== Notes: [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. [2] The condition number is large, 1.49e+07. This might indicate that there are strong multicollinearity or other numerical problems. """
pipe 方法受 Unix 管道的启发,最近也受到了 dplyr 和 magrittr 的影响,它们引入了流行的 (%>%)(读作 pipe)运算符用于 R。这里的 pipe 实现非常简洁,并且在 Python 中感觉很合适。我们鼓励您查看 pipe() 的源代码。
按行或按列应用函数
可以使用 apply() 方法沿着 DataFrame 的轴应用任意函数,与描述性统计方法一样,它接受一个可选的 axis 参数:
In [145]: df.apply(lambda x: np.mean(x)) Out[145]: one 0.811094 two 1.360588 three 0.187958 dtype: float64 In [146]: df.apply(lambda x: np.mean(x), axis=1) Out[146]: a 1.583749 b 0.734929 c 1.133683 d -0.166914 dtype: float64 In [147]: df.apply(lambda x: x.max() - x.min()) Out[147]: one 1.051928 two 1.632779 three 1.840607 dtype: float64 In [148]: df.apply(np.cumsum) Out[148]: one two three a 1.394981 1.772517 NaN b 1.738035 3.684640 -0.050390 c 2.433281 5.163008 1.177045 d NaN 5.442353 0.563873 In [149]: df.apply(np.exp) Out[149]: one two three a 4.034899 5.885648 NaN b 1.409244 6.767440 0.950858 c 2.004201 4.385785 3.412466 d NaN 1.322262 0.541630
apply() 方法也会根据字符串方法名称进行调度。
In [150]: df.apply("mean") Out[150]: one 0.811094 two 1.360588 three 0.187958 dtype: float64 In [151]: df.apply("mean", axis=1) Out[151]: a 1.583749 b 0.734929 c 1.133683 d -0.166914 dtype: float64
传递给 apply() 的函数的返回类型会影响 DataFrame.apply 的最终输出类型,默认行为如下:
- 如果应用的函数返回一个
Series,最终输出是一个DataFrame。列与应用函数返回的Series的索引匹配。 - 如果应用的函数返回任何其他类型,最终输出是一个
Series。
可以使用result_type覆盖此默认行为,它接受三个选项:reduce、broadcast和expand。这将决定类似列表的返回值如何扩展(或不扩展)为一个DataFrame。
apply()结合一些巧妙的技巧可以用来回答关于数据集的许多问题。例如,假设我们想要提取每列的最大值发生的日期:
In [152]: tsdf = pd.DataFrame( .....: np.random.randn(1000, 3), .....: columns=["A", "B", "C"], .....: index=pd.date_range("1/1/2000", periods=1000), .....: ) .....: In [153]: tsdf.apply(lambda x: x.idxmax()) Out[153]: A 2000-08-06 B 2001-01-18 C 2001-07-18 dtype: datetime64[ns]
您还可以向apply()方法传递其他参数和关键字参数。
In [154]: def subtract_and_divide(x, sub, divide=1): .....: return (x - sub) / divide .....: In [155]: df_udf = pd.DataFrame(np.ones((2, 2))) In [156]: df_udf.apply(subtract_and_divide, args=(5,), divide=3) Out[156]: 0 1 0 -1.333333 -1.333333 1 -1.333333 -1.333333
另一个有用的功能是能够传递 Series 方法来对每列或每行执行一些 Series 操作:
In [157]: tsdf = pd.DataFrame( .....: np.random.randn(10, 3), .....: columns=["A", "B", "C"], .....: index=pd.date_range("1/1/2000", periods=10), .....: ) .....: In [158]: tsdf.iloc[3:7] = np.nan In [159]: tsdf Out[159]: A B C 2000-01-01 -0.158131 -0.232466 0.321604 2000-01-02 -1.810340 -3.105758 0.433834 2000-01-03 -1.209847 -1.156793 -0.136794 2000-01-04 NaN NaN NaN 2000-01-05 NaN NaN NaN 2000-01-06 NaN NaN NaN 2000-01-07 NaN NaN NaN 2000-01-08 -0.653602 0.178875 1.008298 2000-01-09 1.007996 0.462824 0.254472 2000-01-10 0.307473 0.600337 1.643950 In [160]: tsdf.apply(pd.Series.interpolate) Out[160]: A B C 2000-01-01 -0.158131 -0.232466 0.321604 2000-01-02 -1.810340 -3.105758 0.433834 2000-01-03 -1.209847 -1.156793 -0.136794 2000-01-04 -1.098598 -0.889659 0.092225 2000-01-05 -0.987349 -0.622526 0.321243 2000-01-06 -0.876100 -0.355392 0.550262 2000-01-07 -0.764851 -0.088259 0.779280 2000-01-08 -0.653602 0.178875 1.008298 2000-01-09 1.007996 0.462824 0.254472 2000-01-10 0.307473 0.600337 1.643950
最后,apply()接受一个默认为 False 的参数raw,在应用函数之前将每行或每列转换为一个 Series。当设置为 True 时,传递的函数将接收一个 ndarray 对象,如果您不需要索引功能,则具有积极的性能影响。
聚合 API
聚合 API 允许以一种简洁的方式表达可能的多个聚合操作。这个 API 在 pandas 对象中是相似的,参见 groupby API、window API 和 resample API。聚合的入口点是DataFrame.aggregate(),或别名DataFrame.agg()。
我们将使用与上面类似的起始框架:
In [161]: tsdf = pd.DataFrame( .....: np.random.randn(10, 3), .....: columns=["A", "B", "C"], .....: index=pd.date_range("1/1/2000", periods=10), .....: ) .....: In [162]: tsdf.iloc[3:7] = np.nan In [163]: tsdf Out[163]: A B C 2000-01-01 1.257606 1.004194 0.167574 2000-01-02 -0.749892 0.288112 -0.757304 2000-01-03 -0.207550 -0.298599 0.116018 2000-01-04 NaN NaN NaN 2000-01-05 NaN NaN NaN 2000-01-06 NaN NaN NaN 2000-01-07 NaN NaN NaN 2000-01-08 0.814347 -0.257623 0.869226 2000-01-09 -0.250663 -1.206601 0.896839 2000-01-10 2.169758 -1.333363 0.283157
使用单个函数等同于apply()。您还可以将命名方法作为字符串传递。这些将返回聚合输出的Series:
In [164]: tsdf.agg(lambda x: np.sum(x)) Out[164]: A 3.033606 B -1.803879 C 1.575510 dtype: float64 In [165]: tsdf.agg("sum") Out[165]: A 3.033606 B -1.803879 C 1.575510 dtype: float64 # these are equivalent to a ``.sum()`` because we are aggregating # on a single function In [166]: tsdf.sum() Out[166]: A 3.033606 B -1.803879 C 1.575510 dtype: float64
对Series进行单个聚合将返回一个标量值:
In [167]: tsdf["A"].agg("sum") Out[167]: 3.033606102414146
使用多个函数进行聚合
您可以将多个聚合参数作为列表传递。每个传递函数的结果将成为结果DataFrame中的一行。这些自然地从聚合函数命名。
In [168]: tsdf.agg(["sum"]) Out[168]: A B C sum 3.033606 -1.803879 1.57551
多个函数产生多行:
In [169]: tsdf.agg(["sum", "mean"]) Out[169]: A B C sum 3.033606 -1.803879 1.575510 mean 0.505601 -0.300647 0.262585
在Series上,多个函数返回一个由函数名称索引的Series:
In [170]: tsdf["A"].agg(["sum", "mean"]) Out[170]: sum 3.033606 mean 0.505601 Name: A, dtype: float64
传递一个lambda函数将产生一个名为的行:
In [171]: tsdf["A"].agg(["sum", lambda x: x.mean()]) Out[171]: sum 3.033606 <lambda> 0.505601 Name: A, dtype: float64
传递一个命名函数将为该行产生该名称:
In [172]: def mymean(x): .....: return x.mean() .....: In [173]: tsdf["A"].agg(["sum", mymean]) Out[173]: sum 3.033606 mymean 0.505601 Name: A, dtype: float64
使用字典进行聚合
将列名的字典传递给标量或标量列表,以便将它们传递给 DataFrame.agg,允许您自定义将哪些函数应用于哪些列。请注意,结果不以任何特定顺序排列,您可以使用 OrderedDict 来保证顺序。
In [174]: tsdf.agg({"A": "mean", "B": "sum"}) Out[174]: A 0.505601 B -1.803879 dtype: float64
传递类似列表的将生成一个 DataFrame 输出。您将获得所有聚合器的矩阵式输出。输出将由所有唯一的函数组成。那些未在特定列中注意到的将为 NaN:
In [175]: tsdf.agg({"A": ["mean", "min"], "B": "sum"}) Out[175]: A B mean 0.505601 NaN min -0.749892 NaN sum NaN -1.803879
自定义描述
使用 .agg() 可以轻松创建自定义描述函数,类似于内置的描述函数。
In [176]: from functools import partial In [177]: q_25 = partial(pd.Series.quantile, q=0.25) In [178]: q_25.__name__ = "25%" In [179]: q_75 = partial(pd.Series.quantile, q=0.75) In [180]: q_75.__name__ = "75%" In [181]: tsdf.agg(["count", "mean", "std", "min", q_25, "median", q_75, "max"]) Out[181]: A B C count 6.000000 6.000000 6.000000 mean 0.505601 -0.300647 0.262585 std 1.103362 0.887508 0.606860 min -0.749892 -1.333363 -0.757304 25% -0.239885 -0.979600 0.128907 median 0.303398 -0.278111 0.225365 75% 1.146791 0.151678 0.722709 max 2.169758 1.004194 0.896839 ```### Transform API `transform()` 方法返回一个与原始索引相同(大小相同)的对象。此 API 允许您一次提供*多个*操作,而不是一个接一个地提供。它的 API 与 `.agg` API 非常相似。 我们创建了一个类似于上述部分中使用的框架。 ```py In [182]: tsdf = pd.DataFrame( .....: np.random.randn(10, 3), .....: columns=["A", "B", "C"], .....: index=pd.date_range("1/1/2000", periods=10), .....: ) .....: In [183]: tsdf.iloc[3:7] = np.nan In [184]: tsdf Out[184]: A B C 2000-01-01 -0.428759 -0.864890 -0.675341 2000-01-02 -0.168731 1.338144 -1.279321 2000-01-03 -1.621034 0.438107 0.903794 2000-01-04 NaN NaN NaN 2000-01-05 NaN NaN NaN 2000-01-06 NaN NaN NaN 2000-01-07 NaN NaN NaN 2000-01-08 0.254374 -1.240447 -0.201052 2000-01-09 -0.157795 0.791197 -1.144209 2000-01-10 -0.030876 0.371900 0.061932
对整个框架进行转换。.transform() 允许输入函数为:NumPy 函数、字符串函数名称或用户定义的函数。
In [185]: tsdf.transform(np.abs) Out[185]: A B C 2000-01-01 0.428759 0.864890 0.675341 2000-01-02 0.168731 1.338144 1.279321 2000-01-03 1.621034 0.438107 0.903794 2000-01-04 NaN NaN NaN 2000-01-05 NaN NaN NaN 2000-01-06 NaN NaN NaN 2000-01-07 NaN NaN NaN 2000-01-08 0.254374 1.240447 0.201052 2000-01-09 0.157795 0.791197 1.144209 2000-01-10 0.030876 0.371900 0.061932 In [186]: tsdf.transform("abs") Out[186]: A B C 2000-01-01 0.428759 0.864890 0.675341 2000-01-02 0.168731 1.338144 1.279321 2000-01-03 1.621034 0.438107 0.903794 2000-01-04 NaN NaN NaN 2000-01-05 NaN NaN NaN 2000-01-06 NaN NaN NaN 2000-01-07 NaN NaN NaN 2000-01-08 0.254374 1.240447 0.201052 2000-01-09 0.157795 0.791197 1.144209 2000-01-10 0.030876 0.371900 0.061932 In [187]: tsdf.transform(lambda x: x.abs()) Out[187]: A B C 2000-01-01 0.428759 0.864890 0.675341 2000-01-02 0.168731 1.338144 1.279321 2000-01-03 1.621034 0.438107 0.903794 2000-01-04 NaN NaN NaN 2000-01-05 NaN NaN NaN 2000-01-06 NaN NaN NaN 2000-01-07 NaN NaN NaN 2000-01-08 0.254374 1.240447 0.201052 2000-01-09 0.157795 0.791197 1.144209 2000-01-10 0.030876 0.371900 0.061932
这里 transform() 接收了一个函数;这相当于应用 ufunc。
In [188]: np.abs(tsdf) Out[188]: A B C 2000-01-01 0.428759 0.864890 0.675341 2000-01-02 0.168731 1.338144 1.279321 2000-01-03 1.621034 0.438107 0.903794 2000-01-04 NaN NaN NaN 2000-01-05 NaN NaN NaN 2000-01-06 NaN NaN NaN 2000-01-07 NaN NaN NaN 2000-01-08 0.254374 1.240447 0.201052 2000-01-09 0.157795 0.791197 1.144209 2000-01-10 0.030876 0.371900 0.061932
将单个函数传递给 .transform() 与 Series 将产生一个返回的单个 Series。
In [189]: tsdf["A"].transform(np.abs) Out[189]: 2000-01-01 0.428759 2000-01-02 0.168731 2000-01-03 1.621034 2000-01-04 NaN 2000-01-05 NaN 2000-01-06 NaN 2000-01-07 NaN 2000-01-08 0.254374 2000-01-09 0.157795 2000-01-10 0.030876 Freq: D, Name: A, dtype: float64
使用多个函数进行转换
传递多个函数将生成一个列 MultiIndexed DataFrame。第一级将是原始框架的列名;第二级将是转换函数的名称。
In [190]: tsdf.transform([np.abs, lambda x: x + 1]) Out[190]: A B C absolute <lambda> absolute <lambda> absolute <lambda> 2000-01-01 0.428759 0.571241 0.864890 0.135110 0.675341 0.324659 2000-01-02 0.168731 0.831269 1.338144 2.338144 1.279321 -0.279321 2000-01-03 1.621034 -0.621034 0.438107 1.438107 0.903794 1.903794 2000-01-04 NaN NaN NaN NaN NaN NaN 2000-01-05 NaN NaN NaN NaN NaN NaN 2000-01-06 NaN NaN NaN NaN NaN NaN 2000-01-07 NaN NaN NaN NaN NaN NaN 2000-01-08 0.254374 1.254374 1.240447 -0.240447 0.201052 0.798948 2000-01-09 0.157795 0.842205 0.791197 1.791197 1.144209 -0.144209 2000-01-10 0.030876 0.969124 0.371900 1.371900 0.061932 1.061932
将多个函数传递给 Series 将产生一个 DataFrame。结果的列名将是转换函数。
In [191]: tsdf["A"].transform([np.abs, lambda x: x + 1]) Out[191]: absolute <lambda> 2000-01-01 0.428759 0.571241 2000-01-02 0.168731 0.831269 2000-01-03 1.621034 -0.621034 2000-01-04 NaN NaN 2000-01-05 NaN NaN 2000-01-06 NaN NaN 2000-01-07 NaN NaN 2000-01-08 0.254374 1.254374 2000-01-09 0.157795 0.842205 2000-01-10 0.030876 0.969124
使用字典进行转换
传递一个函数字典将允许按列进行选择性转换。
In [192]: tsdf.transform({"A": np.abs, "B": lambda x: x + 1}) Out[192]: A B 2000-01-01 0.428759 0.135110 2000-01-02 0.168731 2.338144 2000-01-03 1.621034 1.438107 2000-01-04 NaN NaN 2000-01-05 NaN NaN 2000-01-06 NaN NaN 2000-01-07 NaN NaN 2000-01-08 0.254374 -0.240447 2000-01-09 0.157795 1.791197 2000-01-10 0.030876 1.371900
传递函数列表的字典将生成一个具有这些选择性转换的 MultiIndexed DataFrame。
In [193]: tsdf.transform({"A": np.abs, "B": [lambda x: x + 1, "sqrt"]}) Out[193]: A B absolute <lambda> sqrt 2000-01-01 0.428759 0.135110 NaN 2000-01-02 0.168731 2.338144 1.156782 2000-01-03 1.621034 1.438107 0.661897 2000-01-04 NaN NaN NaN 2000-01-05 NaN NaN NaN 2000-01-06 NaN NaN NaN 2000-01-07 NaN NaN NaN 2000-01-08 0.254374 -0.240447 NaN 2000-01-09 0.157795 1.791197 0.889493 2000-01-10 0.030876 1.371900 0.609836 ```### 逐元素应用函数 由于并非所有函数都可以进行矢量化(接受 NumPy 数组并返回另一个数组或值),因此 DataFrame 上的方法 `map()` 和类似地 Series 上的方法 `map()` 接受任何 Python 函数,该函数接受一个值并返回一个值。例如: ```py In [194]: df4 = df.copy() In [195]: df4 Out[195]: one two three a 1.394981 1.772517 NaN b 0.343054 1.912123 -0.050390 c 0.695246 1.478369 1.227435 d NaN 0.279344 -0.613172 In [196]: def f(x): .....: return len(str(x)) .....: In [197]: df4["one"].map(f) Out[197]: a 18 b 19 c 18 d 3 Name: one, dtype: int64 In [198]: df4.map(f) Out[198]: one two three a 18 17 3 b 19 18 20 c 18 18 16 d 3 19 19
Series.map() 还有一个附加功能;它可以用于轻松“链接”或“映射”由辅助序列定义的值。这与合并/连接功能密切相关:
In [199]: s = pd.Series( .....: ["six", "seven", "six", "seven", "six"], index=["a", "b", "c", "d", "e"] .....: ) .....: In [200]: t = pd.Series({"six": 6.0, "seven": 7.0}) In [201]: s Out[201]: a six b seven c six d seven e six dtype: object In [202]: s.map(t) Out[202]: a 6.0 b 7.0 c 6.0 d 7.0 e 6.0 dtype: float64 ```### 表格级别的函数应用 可以将 `DataFrames` 和 `Series` 传递给函数。但是,如果函数需要在链中调用,请考虑使用 `pipe()` 方法。 首先进行一些设置: ```py In [140]: def extract_city_name(df): .....: """ .....: Chicago, IL -> Chicago for city_name column .....: """ .....: df["city_name"] = df["city_and_code"].str.split(",").str.get(0) .....: return df .....: In [141]: def add_country_name(df, country_name=None): .....: """ .....: Chicago -> Chicago-US for city_name column .....: """ .....: col = "city_name" .....: df["city_and_country"] = df[col] + country_name .....: return df .....: In [142]: df_p = pd.DataFrame({"city_and_code": ["Chicago, IL"]})
extract_city_name 和 add_country_name 是接受并返回 DataFrames 的函数。
现在比较以下内容:
In [143]: add_country_name(extract_city_name(df_p), country_name="US") Out[143]: city_and_code city_name city_and_country 0 Chicago, IL Chicago ChicagoUS
等同于:
In [144]: df_p.pipe(extract_city_name).pipe(add_country_name, country_name="US") Out[144]: city_and_code city_name city_and_country 0 Chicago, IL Chicago ChicagoUS
pandas 鼓励第二种风格,即方法链。pipe 让您可以在方法链中轻松使用自己或另一个库的函数,与 pandas 的方法一起使用。
在上面的示例中,函数 extract_city_name 和 add_country_name 分别期望 DataFrame 作为第一个位置参数。如果您希望应用的函数将其数据作为,比如说,第二个参数呢?在这种情况下,提供一个元组 (callable, data_keyword) 给 pipe。.pipe 将把 DataFrame 路由到元组中指定的参数。
例如,我们可以使用 statsmodels 进行回归拟合。他们的 API 首先期望一个公式,然后是第二个参数 data 的 DataFrame。我们将函数、关键字对 (sm.ols, 'data') 传递给 pipe:
In [147]: import statsmodels.formula.api as sm In [148]: bb = pd.read_csv("data/baseball.csv", index_col="id") In [149]: ( .....: bb.query("h > 0") .....: .assign(ln_h=lambda df: np.log(df.h)) .....: .pipe((sm.ols, "data"), "hr ~ ln_h + year + g + C(lg)") .....: .fit() .....: .summary() .....: ) .....: Out[149]: <class 'statsmodels.iolib.summary.Summary'> """ OLS Regression Results ============================================================================== Dep. Variable: hr R-squared: 0.685 Model: OLS Adj. R-squared: 0.665 Method: Least Squares F-statistic: 34.28 Date: Tue, 22 Nov 2022 Prob (F-statistic): 3.48e-15 Time: 05:34:17 Log-Likelihood: -205.92 No. Observations: 68 AIC: 421.8 Df Residuals: 63 BIC: 432.9 Df Model: 4 Covariance Type: nonrobust =============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------- Intercept -8484.7720 4664.146 -1.819 0.074 -1.78e+04 835.780 C(lg)[T.NL] -2.2736 1.325 -1.716 0.091 -4.922 0.375 ln_h -1.3542 0.875 -1.547 0.127 -3.103 0.395 year 4.2277 2.324 1.819 0.074 -0.417 8.872 g 0.1841 0.029 6.258 0.000 0.125 0.243 ============================================================================== Omnibus: 10.875 Durbin-Watson: 1.999 Prob(Omnibus): 0.004 Jarque-Bera (JB): 17.298 Skew: 0.537 Prob(JB): 0.000175 Kurtosis: 5.225 Cond. No. 1.49e+07 ============================================================================== Notes: [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. [2] The condition number is large, 1.49e+07. This might indicate that there are strong multicollinearity or other numerical problems.
管道方法受到 Unix 管道以及最近的 dplyr 和 magrittr 的启发,它们引入了流行的 (%>%)(读取管道)操作符用于 R。这里的 pipe 实现非常干净,感觉就像在 Python 中本来就应该有的。我们鼓励您查看 pipe() 的源代码。
行或列的函数应用
可以使用 apply() 方法沿着 DataFrame 的轴应用任意函数,该方法与描述性统计方法类似,都接受一个可选的 axis 参数:
In [145]: df.apply(lambda x: np.mean(x)) Out[145]: one 0.811094 two 1.360588 three 0.187958 dtype: float64 In [146]: df.apply(lambda x: np.mean(x), axis=1) Out[146]: a 1.583749 b 0.734929 c 1.133683 d -0.166914 dtype: float64 In [147]: df.apply(lambda x: x.max() - x.min()) Out[147]: one 1.051928 two 1.632779 three 1.840607 dtype: float64 In [148]: df.apply(np.cumsum) Out[148]: one two three a 1.394981 1.772517 NaN b 1.738035 3.684640 -0.050390 c 2.433281 5.163008 1.177045 d NaN 5.442353 0.563873 In [149]: df.apply(np.exp) Out[149]: one two three a 4.034899 5.885648 NaN b 1.409244 6.767440 0.950858 c 2.004201 4.385785 3.412466 d NaN 1.322262 0.541630
Pandas 2.2 中文官方教程和指南(九·二)(4)https://developer.aliyun.com/article/1509702