将datetime列添加到数字数据框强制值为数字,因此为NaN

时间:2018-06-12 14:20:03

标签: python pandas

我有一个带有数字条目的数据框,我希望将一些数字代码添加为字符串,这些也被视为数字,尽管我尝试指定dtype =' str'而且,因为它们看起来不像数字,所以它们变成了NaNs:

dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
df['codes'] = pd.Series(['3/27', '3/22', '3/23', '3/27', '3/58', '3/29'], dtype='str')
df

产生:

Out[1]: 
                   A         B         C         D codes
2013-01-01 -1.071662  0.322842 -1.364833  1.046144   NaN
2013-01-02 -1.779425  1.403387 -1.603079  2.117234   NaN
2013-01-03 -0.759267 -0.305942  1.310631  0.606185   NaN
2013-01-04  1.610275 -0.681264  0.800195  0.775496   NaN
2013-01-05  1.145720  0.252765 -1.512279 -0.222186   NaN
2013-01-06  1.267579 -1.412583 -0.270927  0.584454   NaN

如何将这些代码作为字符串输入?

1 个答案:

答案 0 :(得分:1)

添加index=df.index以将新SeriesDataFrame对齐:

df['codes'] = pd.Series(['3/27', '3/22', '3/23', '3/27', '3/58', '3/29'], index=df.index)

或指定列表:

df['codes'] = ['3/27', '3/22', '3/23', '3/27', '3/58', '3/29']