这种任务对 Pandas 来说简直是小菜一碟 :)
你只需要stack你的DataFrame:
>>> import pandas as pd
>>> # First you need to make `iyear` as index when reading csv to DataFrame.
>>> df = pd.read_csv('eu_terrorism_fatalities_by_country.csv', index_col=0)
>>> df.iloc[0:5, 0:3] # Take a look
Belgium Denmark France
iyear
1970 0 0 0
1971 0 0 0
1972 0 0 1
1973 0 0 5
1974 0 0 3
>>> res = df.stack() # Just this simple :D
>>> res.head() # That's it.
iyear
1970 Belgium 0
Denmark 0
France 0
Germany 0
Greece 2
dtype: int64
注意结果res是一个MultiIndex Series,还有一些后续:
>>> res.index.names = ['year', 'country']
>>> res.name = 'value'
>>> res.head()
year country
1970 Belgium 0
Denmark 0
France 0
Germany 0
Greece 2
Name: value, dtype: int64
>>> res.to_csv('results.csv', header=True)
在results.csv 文件中:
year,country,value
1970,Belgium,0
1970,Denmark,0
1970,France,0
... ...
2014,Portugal,0
2014,Spain,0
2014,United Kingdom,0
跟进您的评论,如果您想将 MultiIndex Series res 转换为 DataFrame,只需 reset_index 并使用它的 args 控制行为:
>>> flat = res.reset_index()
>>> flat.head()
year country value
0 1970 Belgium 0
1 1970 Denmark 0
2 1970 France 0
3 1970 Germany 0
4 1970 Greece 2
>>> flat2 = res.reset_index(level=1)
>>> flat2.head()
country value
year
1970 Belgium 0
1970 Denmark 0
1970 France 0
1970 Germany 0
1970 Greece 2