比较另一列中 python pandas 中的缺失值
Compare missing values in python pandas from another column
我有一个 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']
您可以将 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
没有 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
我有一个 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']
您可以将 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
没有 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