熊猫:将日期'对象'转换为int

jab*_*bba 4 python type-conversion pandas

我有一个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) 
Run Code Online (Sandbox Code Playgroud)

样本数据:

    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
Run Code Online (Sandbox Code Playgroud)

我想我已经尝试了一切,但没有任何作用

test_df['Date'].astype(int):
Run Code Online (Sandbox Code Playgroud)

TypeError:int()参数必须是字符串,类字节对象或数字,而不是'datetime.date'

test_df['Date']=pd.to_numeric(test_df['Date']):
Run Code Online (Sandbox Code Playgroud)

TypeError:位置0处的对象类型无效

test_df['Date'].astype(str).astype(int):
Run Code Online (Sandbox Code Playgroud)

ValueError:基数为10的int()的无效文字:'2014-03-29'

test_df['Date'].apply(pd.to_numeric, errors='coerce'):
Run Code Online (Sandbox Code Playgroud)

将整个列转换为NaN

Ner*_*ksi 10

之所以test_df['Date'].astype(int)给出错误,是因为您的日期仍然包含连字符" - ".首先通过执行来抑制它们test_df['Date'].str.replace("-",""),然后您可以将第一个方法应用于结果系列.所以整个解决方案是:

test_df['Date'].str.replace("-","").astype(int) 请注意,如果" Date "列不是字符串对象,则此操作无效,通常是在Pandas已将您的系列解析为TimeStamp时.在这种情况下,您可以使用:

test_df['Date'].dt.strftime("%Y%m%d").astype(int)
Run Code Online (Sandbox Code Playgroud)


Rak*_*esh 6

看起来你需要pd.to_datetime().dt.strftime("%Y%m%d").

演示:

import pandas as pd
df = pd.DataFrame({"Date": ["2014-03-29", "2014-03-30", "2014-03-31"]})
df["Date"] = pd.to_datetime(df["Date"]).dt.strftime("%Y%m%d")
print( df )
Run Code Online (Sandbox Code Playgroud)

输出:

       Date
0  20140329
1  20140330
2  20140331
Run Code Online (Sandbox Code Playgroud)