【问题标题】:Efficient method to add values in a pandas df在熊猫df中添加值的有效方法
【发布时间】:2019-03-04 09:18:53
【问题描述】:

我正在尝试确定更有效地在pandas df 中添加特定值。

对于下面的df,我想在Value 中为Area 中的每个X + Y 添加integers。因此,对于每个X,我想将其添加到以下Y

import pandas as pd

d = ({
    'Area' : ['X','Y','Z','X','Y','Z'],                                     
    'Value' : [10,11,20,21,30,31],                                     
     })

df = pd.DataFrame(data=d)

如果没有太多值,我可以按照以下方式手动完成:

x = df.iloc[0] + df.iloc[1]

但如果df 相当大,这将变得低效。

预期输出:

21
51

【问题讨论】:

    标签: python pandas add


    【解决方案1】:

    boolean indexing过滤到Series,创建默认索引和Series.add

    s1 = df.loc[df['Area'].eq('X'), 'Value'].reset_index(drop=True)
    s2 = df.loc[df['Area'].eq('Y'), 'Value'].reset_index(drop=True)
    
    s = s1.add(s2)
    print (s)
    0    21
    1    51
    dtype: int64
    

    解决方案的优势不是XY 值的重要顺序。

    【讨论】:

      【解决方案2】:

      在每 2 个索引和 sum() 上使用 XY 和 groupby 创建一个掩码,使用:

      m=df[df.Area.isin(['X','Y'])].reset_index(drop=True)
      print(m.groupby(m.index//2)['Value'].sum())
      

      输出

         0    21
         1    51
      

      【讨论】:

        猜你喜欢
        • 2017-07-29
        • 2021-08-18
        • 1970-01-01
        • 1970-01-01
        • 2016-09-18
        • 2021-05-20
        • 1970-01-01
        • 2017-05-08
        • 2022-09-23
        相关资源
        最近更新 更多