我有一个以下数据框:
dis Country Price
0 0.8 US 500
1 0.8 England 1000
2 0.8 Spain 1500
3 0.8 Portugal 600
4 0.8 Germany 900
5 0.9 US 2200
6 0.9 England 3000
7 0.9 Spain 600
8 0.9 Portugal 1000
9 0.9 Germany 4000
虽然我想按以下方式重新排列它:
dis US England Spain Portugal Germany<br/>
0.8 500 1000 1500 600 900
0.9 2200 3000 600 1000 4000
我很乐意提供一些解决此问题的想法。
最佳答案
假设pandas
,你可以使用set_index
和unstack
来做你想做的事情,只要没有重复索引:
>>> import pandas as pd
>>> df = pd.DataFrame({'dis': [0.8, 0.8, 0.9, 0.9], 'Country':['US', 'England', 'US', 'England'], 'Price':[500, 1000, 1500, 2000]})
>>> df
Country Price dis
0 US 500 0.8
1 England 1000 0.8
2 US 1500 0.9
3 England 2000 0.9
>>> df.set_index(['dis', 'Country']).unstack()
Price
Country England US
dis
0.8 1000 500
0.9 2000 1500
关于python - 重新排列表中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38364279/