【问题标题】:How to substring a column in pandas dataframe如何在熊猫数据框中对列进行子串化
【发布时间】:2019-04-07 07:59:49
【问题描述】:
我在熊猫数据框 YYYY 和 MM 中有 2 列。我想像 YYYYMM 一样连接。但问题是 2019 年 3 月变成 20193 年,2019 年 10 月变成 201910 年。我无法根据这种输出进行排序。我希望所有月份都应该有 2 位数,例如三月月份应该像 03,四月像 04。
如何正确连接它们?
df['YYYY']=df['Order_Date'].dt.year.astype(str)
df['MM']=df['Order_Date'].dt.month.astype(str)
df['YM'] = df.YYYY + df.MM #(this does not solve problem)
预计201903 201904 201910
实际
20193
20194
201910
【问题讨论】:
标签:
python
numpy
dataframe
【解决方案1】:
使用Series.dt.strftime:
df = pd.DataFrame({'Order_Date':pd.date_range('2019-01-01', periods=5 ,freq='m')})
df['YM'] = df['Order_Date'].dt.strftime('%Y%m')
print (df)
Order_Date YM
0 2019-01-31 201901
1 2019-02-28 201902
2 2019-03-31 201903
3 2019-04-30 201904
4 2019-05-31 201905
您的解决方案应该使用 Series.str.zfill:
df['YM'] = (df['Order_Date'].dt.year.astype(str) +
df['Order_Date'].dt.month.astype(str).str.zfill(2))
print (df)
Order_Date YM
0 2019-01-31 201901
1 2019-02-28 201902
2 2019-03-31 201903
3 2019-04-30 201904
4 2019-05-31 201905