我有一个关于添加具有不同类型值的列表的问题: 例如表的长度是10行。第一个给出1月1日,2月1日第2行,3行-1行军等。
是否有一个功能可以启用此功能,而不是手动编写所有内容"。
提前致谢。
答案 0 :(得分:2)
我认为您需要帮助DataFrame
然后join
列为原始。
注意:
index
df
为默认值,表示唯一,单调(0,1,2...
)
#create date range longer as max length of original df
df1 = pd.DataFrame({'rng': pd.date_range('2016-01-01', periods=1000)})
#convert to string and remove trailing 0
df1['new'] = df1['rng'].dt.strftime('%d of %B').str.lstrip('0')
#extract year, month, days
df1 = df1.assign(year=df1['rng'].dt.year,month=df1['rng'].dt.month, day=df1['rng'].dt.day)
#sorting and create default index (0,1,2)
df1 = df1.sort_values(['year','day','month']).reset_index(drop=True)
print (df1.head())
rng new day month year
0 2016-01-01 1 of January 1 1 2016
1 2016-02-01 1 of February 1 2 2016
2 2016-03-01 1 of March 1 3 2016
3 2016-04-01 1 of April 1 4 2016
4 2016-05-01 1 of May 1 5 2016
df = pd.DataFrame({'A':list('abcdef'),
'B':[4,5,4,5,5,4]})
df = df.join(df1['new'])
print(df)
A B new
0 a 4 1 of January
1 b 5 1 of February
2 c 4 1 of March
3 d 5 1 of April
4 e 5 1 of May
5 f 4 1 of June