如何阻止pandas尝试将字符串转换为浮点数?

时间:2016-07-06 08:15:30

标签: python pandas types type-conversion

我正在阅读一个excel文件,并希望将datetime列删除到每月1日。 deprication工作正常,但是pandas尝试将字符串转换为浮点数,并在将其添加为现有数据帧的库存时抛出错误。

如何禁用此功能,只需获取字符串或日期类型的列?

我尝试了不同的映射/类型转换而没有效果(相同的错误)。 如果我转换为代理int,类型转换问题消失(因为它可以将它转换为浮动)但它是一个丑陋的解决方法而不是解决实际问题。

说明问题的代码段

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)

1 个答案:

答案 0 :(得分:0)

您可以访问day属性并从日期时间减去TimedeltaIndex并转换为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)

应该有效