我有一个 Pandas 数据框,我需要将包含日期的列转换为 int,但不幸的是,所有给定的解决方案最终都会出现错误(如下)
test_df.info()
<class 'pandas.core.frame.DataFrame'>
Data columns (total 4 columns):
Date 1505 non-null object
Avg 1505 non-null float64
TotalVol 1505 non-null float64
Ranked 1505 non-null int32
dtypes: float64(2), int32(1), object(1)
示例数据:
Date Avg TotalVol Ranked
0 2014-03-29 4400.000000 0.011364 1
1 2014-03-30 1495.785714 4.309310 1
2 2014-03-31 1595.666667 0.298571 1
3 2014-04-01 1523.166667 0.270000 1
4 2014-04-02 1511.428571 0.523792 1
我想我已经尝试了一切,但没有任何效果
test_df['Date'].astype(int):
类型错误:int() 参数必须是字符串、类似字节的对象或数字,而不是“datetime.date”
test_df['Date']=pd.to_numeric(test_df['Date']):
类型错误:位置 0 处的对象类型无效
test_df['Date'].astype(str).astype(int):
ValueError:以 10 为基数的 int() 的文字无效:'2014-03-29'
test_df['Date'].apply(pd.to_numeric, errors='coerce'):
将整列转换为 NaN
最佳答案
test_df['Date'].astype(int)
给您带来错误的原因是您的日期仍然包含连字符“-”。首先通过执行 test_df['Date'].str.replace("-","")
来抑制它们,然后您可以将第一个方法应用于结果系列。所以整个解决方案是:
test_df['Date'].str.replace("-","").astype(int)
请注意,如果您的“日期”列不是字符串对象,通常当 Pandas 已将您的系列解析为时间戳时,此方法将不起作用。在这种情况下,您可以使用:
test_df['Date'].dt.strftime("%Y%m%d").astype(int)
关于python - Pandas:将日期 'object' 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50863691/