比较python中其他列中缺少的值

2024-10-02 00:19:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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']

Tags: of数据标记dataframepandasdfinputoutput
2条回答

您可以将apply()与查找dict一起使用

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

相关问题 更多 >

    热门问题