python - 合并列以创建带有标题的日期
问题描述
我正在使用一个大型气候文件,其中有 YYYY、MM、DD 列。我想合并这些以创建一个日期列,同时将所有原始数据保留在数据集中。
到目前为止,我已经设法做到了这一点,这几乎得到了我想要的东西,但我似乎无法在日期列中找到标题。
climate = pd.read_csv(r'R:\Climate\SILO\PatchedPoint\Current_csv\86090.csv')
climate.apply(pd.to_numeric, errors = 'ignore')
climate_nozero = climate.drop([0])
climate2 = climate_nozero.rename(columns = {'YYYY':'Year','MM':'Month','DD':'Day'})
index = climate2.apply(lambda x: pd.datetime.strptime("{0} {1} {2}".format(x['Year'],x['Month'], x['Day']), "%Y %m %d"),axis=1)
climate3 = pd.concat([index, climate2], axis=1)
我试过
climate4 = climate3.rename(columns = {'0':'Date'})
更改标题,但它什么也不做
解决方案
假设您的日期列是字符串,您可以像这样assign()
使用to_datetime()
:
df.assign(date = pd.to_datetime(df['YYYY'] + "-" + df['MM'] + "-" + df['DD']))
YYYY MM DD foo date
0 2010 5 1 0 2010-05-01
1 2012 10 2 1 2012-10-02
2 2015 12 3 2 2015-12-03
数据:
data = {"YYYY": ["2010", "2012", "2015"],
"MM": ["5", "10", "12"],
"DD": ["1", "2", "3"],
"foo": range(3)}
df = pd.DataFrame(data)
推荐阅读
- powershell - Powershell检查CSV文件中的变量
- angular - 如何应用样式属性角度自动完成
- python - 有什么方法可以将 dbfs(databricks)路径中的 csv 文件分配给 pyspark 中的变量?
- android - 从底部禁用背景视图
- android - 应用程序崩溃有时在 Fabrics java.lang.RuntimeException 中出现错误:无法恢复活动
- c - 将指针数组设置为 NULL 的标准方法是什么?
- typescript - 声明模块内的多个接口
- botframework - AdaptiveCard C#中的Botframework循环
- excel - 检查单词匹配的功能
- r - R Dismo包:maxent结果的测试AUC和评估()函数的差异