gpt4 book ai didi

python / Pandas : if value is NaN or 0 then fill with the value from the next column within the same row

转载 作者:行者123 更新时间:2023-12-03 23:08:21 25 4
gpt4 key购买 nike

我已经浏览了几篇文章,它们要么仅适用于一列的示例,要么仅适用于 NaN 或 0 值——但不能同时适用于两者。

我的 df 看起来像这样。我想用在它右边的四列中找到的非缺失或非零字符串填写“Main”列。

当前 df =

import pandas as pd

d = {'Main': ['','','',''], 'col2': ['Big','','',0], 'col3': [0,'Medium',0,''], 'col4': ['','','Small',''], 'col5':['',0,'','Vsmall']}
df = pd.DataFrame(data=d)

+------+------+--------+-------+--------+
| Main | Col2 | Col3 | Col4 | Col5 |
+------+------+--------+-------+--------+
| | Big | 0 | ... | |
+------+------+--------+-------+--------+
| | ... | Medium | ... | 0 |
+------+------+--------+-------+--------+
| | | 0 | Small | |
+------+------+--------+-------+--------+
| | 0 | ... | ... | Vsmall |
+------+------+--------+-------+--------+

所需的输出 df
+--------+------+--------+-------+--------+
| Main | Col2 | Col3 | Col4 | Col5 |
+--------+------+--------+-------+--------+
| Big | Big | 0 | ... | |
+--------+------+--------+-------+--------+
| Medium | ... | Medium | ... | 0 |
+--------+------+--------+-------+--------+
| Small | | 0 | Small | |
+--------+------+--------+-------+--------+
| Vsmall | 0 | ... | ... | Vsmall |
+--------+------+--------+-------+--------+

提前致谢!

最佳答案

想法是替换0和空字符串到缺失值 DataFrame.mask ,然后回填缺失的行并最后选择第一列:

c = ['col2','col3','col4','col5']
df['Main'] = df[c].mask(df.isin(['0','',0])).bfill(axis=1).iloc[:, 0]
print (df)
Main col1 col2 col3
0 Big Big None
1 Medium 0 Medium None
2 Small 0 Small

如果可能,创建所有可能提取的字符串的列表,将所有其他值替换为 DataFrame.where :
['col2','col3','col4','col5']
df['Main'] = df[c].where(df.isin(['Big','Medium','Small','Vsmall'])).bfill(axis=1).iloc[:,0]
print (df)
Main col1 col2 col3
0 Big Big None
1 Medium 0 Medium None
2 Small 0 Small

详情 :
print (df[c].mask(df.isin(['0','',0])))
#print (df[c].where(df.isin(['Big','Medium','Small','Vsmall'])))

col1 col2 col3
0 Big None NaN
1 NaN Medium None
2 NaN NaN Small

print (df[c].mask(df.isin(['0','',0])).bfill(axis=1))
col1 col2 col3
0 Big NaN NaN
1 Medium Medium None
2 Small Small Small

关于 python / Pandas : if value is NaN or 0 then fill with the value from the next column within the same row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60824684/

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