gpt4 book ai didi

python - 根据现有列下一行的元素创建新列

转载 作者:行者123 更新时间:2023-11-30 22:05:24 25 4
gpt4 key购买 nike

我正在努力清理和重新构建数据框架。

我有以下数据框:

data= pd.DataFrame()
data['ID'] = [1,1,1,1,1,2,2,2,2,2]
data ['EventSecond'] = [1.5,2,2.5,3,3.8,4,4.8,6,7,8,]
data ['P1'] = ['A','B','C','D','E','F','A','D','E','G']
data ['Code'] = [12,13,16,9,9,0,4,13,14,16]
data ['status'] =['Pass','Pass','Pass','Pass','Pass','Pass','shot','shot','Pass','Pass']
data ['Accuracy']= ['Accurate','Accurate','Accurate','Accurate','Accurate','Not Accurate','Accurate','Accurate','Accurate','Not Accurate']

在此数据框中,我有 ID、Eventsecond 等。我想要做的是创建一个新列 P2,如果 Accuracy 列的元素是 准确,则它包含 P1 列下一行的元素>。一件事是,如果下面的 ID 列不同,我不会从下面的行中获取元素并将其留空如果准确性不准确,我会将此行留空。

问题补充

我只会获取状态列值为通过的行。

预期输出如下:

enter image description here

有人可以建议一下吗?谢谢,

泽普。

最佳答案

IIUC,您需要groupbytransform:

mask = (data['status'].isin(['Pass','pass']))
data.loc[mask,'P2'] = data[mask].groupby('ID')['P1'].transform(lambda x: x.shift(-1))
data.loc[data['Accuracy']=='Not Accurate','P2'] = np.nan

或仅使用过滤器:

mask = (data['status'].isin(['Pass','pass']))
data.loc[mask,'P2'] = data.loc[mask,'P1'].shift(-1)
mask2 = data['ID'].ne(data['ID'].shift(-1))|data['status'].eq('shot')|data['Accuracy'].eq('Not Accurate')
data.loc[mask2,'P2'] = ''
<小时/>
print(data)
ID EventSecond P1 Code status Accuracy P2
0 1 1.5 A 12 Pass Accurate B
1 1 2.0 B 13 Pass Accurate C
2 1 2.5 C 16 Pass Accurate D
3 1 3.0 D 9 Pass Accurate E
4 1 3.8 E 9 Pass Accurate NaN
5 2 4.0 F 0 Pass Not Accurate NaN
6 2 4.8 A 4 shot Accurate NaN
7 2 6.0 D 13 shot Accurate NaN
8 2 7.0 E 14 pass Accurate G
9 2 8.0 G 16 pass Not Accurate NaN

如果你什么空白然后使用:而不是 NAN:

print(data.fillna(''))

ID EventSecond P1 Code status Accuracy P2
0 1 1.5 A 12 Pass Accurate B
1 1 2.0 B 13 Pass Accurate C
2 1 2.5 C 16 Pass Accurate D
3 1 3.0 D 9 Pass Accurate E
4 1 3.8 E 9 Pass Accurate
5 2 4.0 F 0 Pass Not Accurate
6 2 4.8 A 4 shot Accurate
7 2 6.0 D 13 shot Accurate
8 2 7.0 E 14 pass Accurate G
9 2 8.0 G 16 pass Not Accurate

关于python - 根据现有列下一行的元素创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53031442/

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