gpt4 book ai didi

python - 使用 DataFrame 中不同组内的引用行来执行数据操作

转载 作者:行者123 更新时间:2023-12-02 18:48:51 25 4
gpt4 key购买 nike

给定这个数据框

df = pd.DataFrame({'Group': {0: 'a', 1: 'a', 2: 'b', 3: 'b', 4: 'c', 5: 'c', 6: 'd', 7: 'd'},
'Time': {0: 0, 1: 1, 2: 0, 3: 1, 4: 0, 5: 1, 6: 0, 7: 1},
'Mean': {0: 1, 1: 4, 2: 1, 3: 5, 4: 2, 5: 6, 6: 2, 7: 9}})

对于 DataFrame 中的每个组(ab),我想获取 Mean 列中的每个数字并将其除以通过 Time == 0 处的相应值,并获取该值的 np.log2。换句话说,我想以这个结束

df2 = pd.DataFrame({'Group': {0: 'a', 1: 'a', 2: 'b', 3: 'b', 4: 'c', 5: 'c', 6: 'd', 7: 'd'},
'Time': {0: 0, 1: 1, 2: 0, 3: 1, 4: 0, 5: 1, 6: 0, 7: 1},
'Mean': {0: 1, 1: 4, 2: 1, 3: 5, 4: 2, 5: 6, 6: 2, 7: 9},
'New': {0: 0.0, 1: 2.0, 2: 0.0, 3: 2.321928094887362, 4: 0.0, 5: 1.584962500721156, 6: 0.0, 7: 2.169925001442312}})

目前我通过以下方式实现了这一目标

df2 = pd.DataFrame()
for group, sub in df.groupby('Group'):
sub['New'] = np.log2(sub.Mean / sub.Mean.iloc[0])
df2 = pd.concat([df2, sub], axis=0)

但我觉得应该有一个更简单的方法。

最佳答案

你可以做groupby与变换first (替换 iloc[0] ),然后除以 Mean专栏。

df['New'] = np.log2(df['Mean']/df.groupby("Group")['Mean'].transform('first'))

  Group  Time  Mean       New
0 a 0 1 0.000000
1 a 1 4 2.000000
2 b 0 1 0.000000
3 b 1 5 2.321928
4 c 0 2 0.000000
5 c 1 6 1.584963
6 d 0 2 0.000000
7 d 1 9 2.169925

编辑:

如果您不确定 Time 等于 0 的索引,也可以执行以下操作:

df['New'] = (np.log2(df['Mean']/df.loc[df['Time'].eq(0).groupby(df['Group'])
.transform('idxmax'),'Mean'].to_numpy()))

当 cond Time=0 为 True 时,这将为每个组返回最大索引。 ,然后使用 df.loc我们返回平均列并将其用于除法。有关详细信息,请参阅如何 idxmax 作品


print(df)

Group Time Mean New
0 a 0 1 0.000000
1 a 1 4 2.000000
2 b 0 1 0.000000
3 b 1 5 2.321928
4 c 0 2 0.000000
5 c 1 6 1.584963
6 d 0 2 0.000000
7 d 1 9 2.169925

关于python - 使用 DataFrame 中不同组内的引用行来执行数据操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67061561/

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