【问题标题】:Use apply & lambda for serie对系列使用 apply 和 lambda
【发布时间】:2016-10-29 14:25:00
【问题描述】:

我有这个:

df.loc['United Kingdom']

这是一个系列:

Rank                        4.000000e+00
Documents                   2.094400e+04
Citable documents           2.035700e+04
Citations                   2.060910e+05
Self-citations              3.787400e+04
Citations per document      9.840000e+00
H index                     1.390000e+02
Energy Supply                        NaN
Energy Supply per Capita             NaN
% Renewable's                        NaN
2006                        2.419631e+12
2007                        2.482203e+12
2008                        2.470614e+12
2009                        2.367048e+12
2010                        2.403504e+12
2011                        2.450911e+12
2012                        2.479809e+12
2013                        2.533370e+12
2014                        2.605643e+12
2015                        2.666333e+12
Name: United Kingdom, dtype: float64

现在,我想得到

应用(lambda x: x['2015'] - x['2006'])

但是它返回了一个错误:

TypeError: 'float' 对象不可下标

但如果我把它分开:

df.loc['United Kingdom']['2015'] - df.loc['United Kingdom']['2006']

一切正常。

我如何在这里申请和 lambda?

谢谢。

Ps:我想将它应用到 Dataframe

Rank    Documents   Citable documents   Citations   Self-citations  Citations per document  H index Energy Supply   Energy Supply per Capita    % Renewable's   ... 2008    2009    2010    2011    2012    2013    2014    2015    Citation Ratio  Population
Country                                                                                 
China   1   127050  126767  597237  411683  4.70    138 NaN NaN NaN ... 4.997775e+12    5.459247e+12    6.039659e+12    6.612490e+12    7.124978e+12    7.672448e+12    8.230121e+12    8.797999e+12    0.689313    NaN
United States   2   96661   94747   792274  265436  8.20    230 NaN NaN NaN ... 1.501149e+13    1.459484e+13    1.496437e+13    1.520402e+13    1.554216e+13    1.577367e+13    1.615662e+13    1.654857e+13    0.335031    NaN
Japan   3   30504   30287   223024  61554   7.31    134 NaN NaN NaN ... 5.558527e+12    5.251308e+12    5.498718e+12    5.473738e+12    5.569102e+12    5.644659e+12    5.642884e+12    5.669563e+12    0.275997    NaN
United Kingdom  4   20944   20357   206091  37874   9.84    139 NaN NaN NaN ... 2.470614e+12    2.367048e+12    2.403504e+12    2.450911e+12    2.479809e+12    2.533370e+12    2.605643e+12    2.666333e+12    0.183773    NaN
enter code here

【问题讨论】:

  • 为什么要在这里使用apply?您只是得到系列中两个特定值的差异。 apply 用于将某些功能应用于系列中的每个元素。
  • 其实我有一个Dataframe,它只是一个Serie。我想对所有 Dataframe 都这样做。我刚刚更新了我的问题。

标签: python pandas


【解决方案1】:

如果你想将它应用于你的所有数据框,那么只需计算它:

df['2015'] - df['2006']

【讨论】:

    猜你喜欢
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 2012-11-15
    • 2018-12-13
    • 2017-01-27
    • 1970-01-01
    • 2021-03-06
    相关资源
    最近更新 更多