Python 通过排除表中另一列中的特定值来填充一列

Python 通过排除表中另一列中的特定值来填充一列,python,pandas,Python,Pandas,对于数据帧df,如果列a中的值为空NaNs或其他,我将尝试按值填充列b: df = pd.DataFrame({'a':['Coffee','Muffin','Donut','Others',pd.np.nan, pd.np.nan]}) a 0 Coffee 1 Muffin 2 Donut 3 Others 4 NaN 5 NaN df.loc[~df['a'].fillna('Others').eq('Others'), 'b'] = '2017

对于数据帧
df
,如果列
a
中的值为空
NaNs
其他
,我将尝试按值填充列
b

df = pd.DataFrame({'a':['Coffee','Muffin','Donut','Others',pd.np.nan, pd.np.nan]})
        a
0  Coffee
1  Muffin
2   Donut
3  Others
4     NaN
5     NaN
df.loc[~df['a'].fillna('Others').eq('Others'), 'b'] = '2017-01-01'
print (df)
        a           b
0  Coffee  2017-01-01
1  Muffin  2017-01-01
2   Donut  2017-01-01
3  Others         NaN
4     NaN         NaN
5     NaN         NaN
预期结果如下:

        a           b
0  Coffee  2017-01-01
1  Muffin  2017-01-01
2   Donut  2017-01-01
3  Others         NaN
4     NaN         NaN
5     NaN         NaN
我尝试过的没有排除NaNs的内容:

df.loc[~df['a'].isin(['nan', 'Others']), 'b'] = '2017-01-01'

        a           b
0  Coffee  2017-01-01
1  Muffin  2017-01-01
2   Donut  2017-01-01
3  Others         NaN
4     NaN  2017-01-01
5     NaN  2017-01-01

谢谢

使用
np.nan
代替
nan

df.loc[~df['a'].isin([np.nan, 'Others']), 'b'] = '2017-01-01'
或在比较之前,用
其他替换缺少的值

df = pd.DataFrame({'a':['Coffee','Muffin','Donut','Others',pd.np.nan, pd.np.nan]})
        a
0  Coffee
1  Muffin
2   Donut
3  Others
4     NaN
5     NaN
df.loc[~df['a'].fillna('Others').eq('Others'), 'b'] = '2017-01-01'
print (df)
        a           b
0  Coffee  2017-01-01
1  Muffin  2017-01-01
2   Donut  2017-01-01
3  Others         NaN
4     NaN         NaN
5     NaN         NaN
看看这个:

import numpy as np
import pandas as pd

df = pd.DataFrame({'a': ['Coffee', 'Muffin', 'Donut', 'Others', pd.np.nan, pd.np.nan]})
conditions = [
    (df['a'] == 'Others'),
    (df['a'].isnull())
]
choices = [np.nan, np.nan]
df['color'] = np.select(conditions, choices, default='2017-01-01')

print(df)

你能给我看一下你输入的得到结果的代码吗?对不起,我错过了。已更新。如果不是“NaN”或“others”,您似乎正在尝试填写日期字符串是的,只是示例数据。谢谢,我有一个问题,为什么您需要两个日期作为
选项
?每个条件一个选项