gpt4 book ai didi

python - 用条件填充列

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:55 25 4
gpt4 key购买 nike

我有一个包含 2 列的数据框:

          Col1          Col2
1 NaN Someval1
2 Y Someval2
3 N Someval3
4 NaN NaN
5 NaN Someval4

我想用以下条件填充 NaN:

If Col1 has NaN and Col2 has a Someval1 that is in list 1 then fillna with Y
If Col1 has NaN and Col2 has a Someval4 that is in list 2 then fillna with N
If Col1 has NaN and Col2 has a NaN that is in list 2 then fillna with N

有什么建议吗? (不知道可不可以)

非常感谢!

最佳答案

我想你需要mask , 对于条件 isnullisin :

L1 = ['Someval1','Someval8']
L2 = ['Someval4','Someval9', np.nan]
m1 = df['Col1'].isnull()
m2 = df['Col2'].isin(L1)
m3 = df['Col2'].isin(L2)

df['Col1'] = df['Col1'].mask(m1 & m2, 'Y')
df['Col1'] = df['Col1'].mask(m1 & m3, 'N')

print (df)
Col1 Col2
1 Y Someval1
2 Y Someval2
3 N Someval3
4 N NaN
5 N Someval4

另一种解决方案 numpy.where :

df['Col1'] = np.where(m1 & m2, 'Y',
np.where(m1 & m3, 'N', df['Col1']))

print (df)
Col1 Col2
1 Y Someval1
2 Y Someval2
3 N Someval3
4 N NaN
5 N Someval4

具有一个条件和fillna的另一种解决方案:

L1 = ['Someval1','Someval8']
L2 = ['Someval4','Someval9', np.nan]

df['Col1'] = df['Col1'].mask(df['Col2'].isin(L1), df['Col1'].fillna('Y'))
df['Col1'] = df['Col1'].mask(df['Col2'].isin(L2), df['Col1'].fillna('N'))
print (df)
Col1 Col2
1 Y Someval1
2 Y Someval2
3 N Someval3
4 N NaN
5 N Someval4

关于python - 用条件填充列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44775764/

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