我想在列表中的每一年重复一个df。
df每次重复时,也应在称为“ year”的新列中添加与迭代相对应的年份。
我有:
>>> ls = ['2019','2018','2017','2016']
>>> df = pd.DataFrame(['a','b'])
>>> df
0
0 a
1 b
我想要:
>>> df
0 year
0 a '2019'
1 b '2019'
2 a '2018'
3 b '2018'
4 a '2017'
5 b '2017'
6 a '2016'
7 b '2016'
import pandas as pd
ls = ['2019','2018','2017','2016','2015']
col = []
for i, year in enumerate(ls):
col.append('b' if i%2 else 'a')
df = pd.DataFrame.from_dict({
'0': col,
'year': ls,
})
print(df)
输出:
0 year
0 a 2019
1 b 2018
2 a 2017
3 b 2016
4 a 2015