我正在读取一个Excel文件,并希望将datetime列的值分隔为每个月的1号。贬值工作正常,但熊猫尝试将字符串隐藏起来使其浮起,并在将其添加为现有数据帧的同伴时抛出错误。
如何禁用此功能,仅获取具有字符串或日期类型的列?
我尝试了各种映射/类型转换,但没有效果(错误)。如果我转换为proxy int,类型转换问题将消失(因为它可以将其转换为float),但这是一个丑陋的解决方法,而不是解决实际问题。
说明该问题的代码段
df = pd.read_excel(file_name, skiprows=[1], skip_footer=1)
print(df['Purch.Date'].dtype)
>>> datetime64[ns]
print(df['Purch.Date'].head())
>>> 0 2016-06-23
>>> 1 2016-06-09
>>> 2 2016-06-24
>>> 3 2016-06-24
>>> 4 2016-06-24
df['YearMonthCapture'] = df['Purch.Date'].map(lambda x: str(x.replace(day=1).date()) ).astype(str)
>>> ValueError: could not convert string to float: '2016-06-01'
# === Other approached resulting in same error ===
#df['YearMonthCapture'] = df['Purch.Date'].map(lambda x: x.replace(day=1))
#df['YearMonthCapture'] = pd.Series(df['Purch.Date'].map(lambda x: str(x.replace(day=1).date()) ), dtype='str')
#df['YearMonthCapture'] = pd.Series(df['Purch.Date'].apply(lambda x: str(x.replace(day=1).date()) ), dtype='str')
# === Ugly work around that does not really address the problem) ===
df['YearMonthCapture'] = pd.Series(df['Purch.Date'].apply(lambda x: 100*x.year + x.month)
您可以通过访问day
属性并TimedeltaIndex
从日期时间中减去a并将其强制转换为str来实现:
In [138]:
df = pd.DataFrame({'date':pd.date_range(dt.datetime(2016,1,1), periods=4)})
df
Out[138]:
date
0 2016-01-01
1 2016-01-02
2 2016-01-03
3 2016-01-04
In [142]:
(df['date'] - pd.TimedeltaIndex(df['date'].dt.day - 1, unit='D')).astype(str)
Out[142]:
0 2016-01-01
1 2016-01-01
2 2016-01-01
3 2016-01-01
Name: date, dtype: object
因此,在您的情况下:
df['YearMonthCapture'] = (df['Purch.Date'] - pd.TimedeltaIndex(df['Purch.Date'].dt.day - 1, unit='D')).astype(str)
应该管用
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句