python - 重新排列表中的数据

标签 python

我有一个以下数据框:

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_indexunstack来做你想做的事情,只要没有重复索引:

>>> 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/

相关文章:

python - 当我注册用户时,页面上没有密码字段

python * 运算符,创建具有默认值的列表

python - 如何查看 2 个日期产生的收入超过 1 个日期的总收入的实例有多少?

python - 在基于 Python 的 DSL 中自定义异常的回溯

python - 意外的缩进错误,但缩进看起来是正确的

python - Django 字段的默认值是什么?

python - Python:同时执行多个无限循环

python - python中的命令行工具位于固定根目录中

python - 通过移动索引移动二维数组中的数据

python - 如何在 Python 中从控制台删除未知用户输入