python - Pandas:将日期 'object' 转换为 int

标签 python pandas type-conversion

我有一个 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/

相关文章:

python - 如何用线性回归绘制散点图?

python - 接收器丢失通过python中的TCP套接字发送的文件丢失的最后相同字节

Python Pandas - 与 Scipy 的优势比(P 值 = 0?)

python - 如何选择数据框中的特定列?

c# - 是否可以为 XAttribute 和 XElement 编写方法?

python - 按行和列获取单元格的值

python - 清除 rpy2 使用的内存

python - pandas to_csv ,唯一记录数量减少

java - 是否有与 java.lang.Number 等效的 C++?

java - MediaWiki 到纯文本转换