gpt4 book ai didi

python - 加等于 Pandas 数据帧

转载 作者:行者123 更新时间:2023-12-04 07:22:12 24 4
gpt4 key购买 nike

我正在尝试匹配来自两个不同 DataFrame 的值。第一个 DataFrame 有一列的值是名称的组合,如 ('John Bradford', 'Brad Johnford')第二个 DataFrame 有三列“姓名”、“工资”、“百分比”,如下所示

     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 速记来添加每个薪水,然后乘以百分比,但该值返回为空。如果我将 += 更改为仅等于它适用于组合中的名称之一,但不会添加其余的值。
是否有我应该使用的内置函数而不是速记?

最佳答案

我冒昧地从你的工资中删除了逗号,以便将它们加在一起。无论如何,这将做到。
基本上你可以分解元组,加入第二个数据帧,并使用原始索引进行分组和聚合。然后,您可以将其连接回原始 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

关于python - 加等于 Pandas 数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68424222/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com