Python 熊猫:转换日期';对象';整型
我有一个Pandas数据框,我需要将一个带有日期的列转换为int,但不幸的是,所有给定的解决方案最终都会出错(如下所示) 我想我什么都试过了,但都没用Python 熊猫:转换日期';对象';整型,python,pandas,type-conversion,Python,Pandas,Type Conversion,我有一个Pandas数据框,我需要将一个带有日期的列转换为int,但不幸的是,所有给定的解决方案最终都会出错(如下所示) 我想我什么都试过了,但都没用 test_df['Date'].astype(int): TypeError:int()参数必须是字符串、类似对象的字节或数字,而不是“datetime.date” test_df['Date']=pd.to_numeric(test_df['Date']): TypeError:位置0处的对象类型无效 test_df['Date'].ast
test_df['Date'].astype(int):
TypeError:int()参数必须是字符串、类似对象的字节或数字,而不是“datetime.date”
test_df['Date']=pd.to_numeric(test_df['Date']):
TypeError:位置0处的对象类型无效
test_df['Date'].astype(str).astype(int):
ValueError:以10为基数的int()的文本无效:“2014-03-29”
test_df['Date'].apply(pd.to_numeric, errors='coerce'):
将整个列转换为NAN这应该可以
df['Date'] = pd.to_numeric(df.Date.str.replace('-',''))
print(df['Date'])
0 20140329
1 20140330
2 20140331
3 20140401
4 20140402
test_df['Date'].astype(int)
给您一个错误的原因是日期仍然包含连字符“-”。首先通过执行test_df['Date'].str.replace(“-”,”)
来抑制它们,然后您可以将第一种方法应用于结果序列。因此,整个解决方案将是:
test_df['Date'].str.replace(“-”,”).astype(int)
请注意,如果“Date”列不是字符串对象,这将不起作用,通常情况下,Pandas已经将序列解析为时间戳。在这种情况下,您可以使用:
test_df['Date'].dt.strftime("%Y%m%d").astype(int)
看起来您需要
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 )
Date
0 20140329
1 20140330
2 20140331
输出:
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 )
Date
0 20140329
1 20140330
2 20140331
把日期转换成整数,你希望得到什么?1970年1月1日以来的几天?月份的整数表示形式?不带连字符的字符串表示全部连接?如果我们不知道,熊猫怎么知道你想从这次行动中得到什么?你希望得到什么?例如,
2014-03-29
应该是什么,以及2014-03-30
应该是什么?预期的输出是一个没有连字符的字符串表示