我有一个pandas数据帧,它由两列值组成。有些值丢失了,我想创建第三列,标记两列中是否有丢失的值,或者是否有一列已填充。我不确定如何做到这一点,因为我是新来的,如果你能提供任何帮助,将不胜感激
#input
df = {'First': ['','','A','B','B','C'],
'Second': ['12', '', '10', '', '', '11']}
df = pd.DataFrame(data = d)
#Possible output of third column
df['Third'] = ['Secondfilled', 'missing', 'bothfilled', 'Firstfilled', 'Firstfilled', bothfilled']
没有ifelse或自定义函数的单行解决方案。改进了@SeaBean的建议!
d = {0: 'Missing', 1: 'FirstFilled', 2: 'SecondFilled', 3: 'BothFilled'}
df['Third'] = (df.ne('')*(1,2)).sum(1).map(d)
输出:
print(df)
First Second Third
0 12 SecondFilled
1 Missing
2 A 10 BothFilled
3 B FirstFilled
4 B FirstFilled
5 C 11 BothFilled
您可以将apply()
与查找字典一起使用。
lookup = {'10': 'Firstfilled', '01': 'Secondfilled', '11': 'bothfilled', '00': 'missing'}
def fill(row):
key = '00'
if row['First'] != '':
key = '1' + key[1]
if row['Second'] != '':
key = key[0] + '1'
return lookup[key]
df['Third'] = df.apply(fill, axis=1)
# print(df)
First Second Third
0 12 Secondfilled
1 missing
2 A 10 bothfilled
3 B Firstfilled
4 B Firstfilled
5 C 11 bothfilled