Python 如何阻止熊猫尝试将字符串转换为浮动?

Python 如何阻止熊猫尝试将字符串转换为浮动?,python,pandas,types,type-conversion,Python,Pandas,Types,Type Conversion,我正在读一个excel文件,想在每个月的1号删除datetime列。 去润滑工作正常,但pandas尝试将字符串转换为浮点数,并在将其添加为现有数据帧的coulmn时抛出错误 我怎样才能禁用它,只获取一个字符串或日期类型的列 我尝试了各种映射/类型转换,但没有效果(相同的错误)。 如果我转换为代理int,类型转换问题就会消失(因为它可以将其转换为float),但这是一个丑陋的解决方法,而不是解决真正的问题 说明问题的代码片段 df = pd.read_excel(file_name, skipr

我正在读一个excel文件,想在每个月的1号删除datetime列。 去润滑工作正常,但pandas尝试将字符串转换为浮点数,并在将其添加为现有数据帧的coulmn时抛出错误

我怎样才能禁用它,只获取一个字符串或日期类型的列

我尝试了各种映射/类型转换,但没有效果(相同的错误)。 如果我转换为代理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
属性并从datetime中减去
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)

应该可以工作

您可以通过访问
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)
应该有用