我这样做是为了家庭作业。
我的目标是创建一个全新的专栏,只记录过去的日子。这有 500,000 多行......所以我的目标是:
- 在 Pandas 数据框中,我有这两个格式不同的日期列。我想减去这两列,然后创建一个新的“Days Elapsed”列,它是一个简单的整数列表。
- 输出到新的 CSV(此代码已完成)
- 现在我可以完全避免每次重新编写代码/读取 CSV 时解析日期,因为这会花费很长时间并减慢我的工作速度。
我正在尝试将其转换为:
Yearmade Saledate
0 2004 11/16/2006 0:00
1 1996 3/26/2004 0:00
2 2001 2/26/2004 0:00
进入:
Days Elapsed
0 1050
1 3007
2 1151
当前尝试:
year_mean = df[df['YearMade'] > 1000]['YearMade'].mean()
df.loc[df['YearMade'] == 1000, 'YearMade'] = year_mean
## There's lots of erroneous data of the year 1000, so replacing all of them with the mean of the column (mean of column without error data, that is)
df['Yearmade'] = "1/1/"+df['YearMade'].astype(str)
## This is where it errors out.
df['Yearmade'] = pd.to_datetime(df['Yearmade'])
df['Saledate'] = pd.to_datetime(df['Saledate'])
df['Age_at_Sale'] = df['Saledate'].sub(df['Yearmade'])
df = df.drop(['Saledate', 'Yearmade'], axis=1)
[then there's another class method to convert the current df into csv]