在python 3.6和pandas 0.19.0中
有一列“日期”
date
2018-01-01
2018-01-02
2018-01-03
2018-01-05
我正在尝试将其转换为NULL = 0,non-NULLvalue = 1
date
1
1
1
0
1
第一步是将null转换为0,这很容易
df['date'] = df['date'].fillna(value=0)
这给了我:
date
2018-01-01
2018-01-02
2018-01-03
0
2018-01-05
但是,我有点坚持将非零值转换为1。在这里,pandas.set_values似乎不是一个好选择。
df['date']=df[(df.date != 0)] == "1"
上面的内容似乎不适用于错误消息:
TypeError: Could not compare ['1'] with block values
有什么想法吗?谢谢!
最佳答案
联合会
pd.to_datetime(df.date,errors='coerce').isnull().astype(int)
Out[862]:
0 0
1 0
2 0
3 1
4 0
Name: date, dtype: int32
或
df.date.isnull().astype(int)
(如果空白已为NaN
)