【问题标题】:Plus equals in pandas dataframe熊猫数据框中的加号等于
【发布时间】:2021-07-18 05:33:25
【问题描述】:

我正在尝试匹配来自两个不同 DataFrame 的值。第一个 DataFrame 有一列的值是 ('John Bradford', 'Brad Johnford') 等名称的组合,第二个 DataFrame 有三列 'Names'、'Salary'、'Percentage',看起来像这样

     Name               Salary       Percentage
'John Bradford'         60,000         .30
'Brad Johnford'         50,000         .40
'Steve Blue'            10,000         .20

我需要将工资总和添加为组合数据框中的一个新列,然后添加一个新的百分比列,每个百分比乘以每个员工组合。

最终的 DataFrame 如下所示

            Combos                  Total Salary    Total Percentage
('John Bradford', 'Steve Blue')        70,000             0.06
('John Bradford', 'Brad Johnford')     110,000            0.12

遍历 DataFrame 直到每个玩家都在组合中被选中。

for index, _ in employee_pool.iterrows():
    for idx, _ in combo_pool.iterrows():
        if employee_pool.at[index, 'Name'] in combo_pool.at[idx, 'Combo']:
            combo_pool.at[idx, 'Salary'] += player_pool.at[index, 'Salary']
            combo_pool.at[idx, 'Percentage'] *= float(player_pool.at[index, 'Percentage'].replace('%', ''))

我尝试使用 plus equals 速记来添加每个薪水,然后乘以百分比,但该值返回为空。如果我将 += 更改为等于,它适用于组合中的一个名称,但不会添加其余值。

我应该使用内置函数来代替速记吗?

【问题讨论】:

  • 结果应该也有('Brad Johnford', 'Steve Blue')吗?
  • 是的,我只是没有添加所有组合

标签: python pandas dataframe


【解决方案1】:

我冒昧地从您的工资中删除了逗号,以便可以将它们加在一起。无论如何,这样就可以了。

基本上,您可以分解元组,加入第二个数据框,并使用原始索引进行分组和聚合。然后,您可以将其连接回原始 df。

df = pd.DataFrame({'Combos':[('John Bradford','Steve Blue'),('John Bradford','Brad Johnford')]})
names = df.Combos.explode().to_frame().reset_index()

df2 = pd.DataFrame({'Name': {0: 'John Bradford', 1: 'Brad Johnford', 2: 'Steve Blue'},
 'Salary': {0: 60000, 1: 50000, 2: 10000},
 'Percentage': {0: 0.3, 1: 0.4, 2: 0.2}})
    
names = names.merge(df2, left_on='Combos', right_on='Name')

pd.concat([df, names.groupby('index').agg({'Salary':sum,'Percentage':np.product})], axis=1)

输出

                           Combos  Salary  Percentage
0     (John Bradford, Steve Blue)   70000        0.06
1  (John Bradford, Brad Johnford)  110000        0.12

【讨论】:

  • 这里不需要 np.product。 Pandas 已经定义了一个 aggfunc {'Salary': 'sum', 'Percentage': 'prod'}
猜你喜欢
  • 1970-01-01
  • 2021-05-31
  • 2016-07-21
  • 2018-07-12
  • 1970-01-01
  • 1970-01-01
  • 2017-01-13
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多