我是 python 新手,我想转置 CSV 格式的文件。我的文件结构如下:
Country;Class;Number
UK;1;50
Germany;2;30
France;3;50
France;1;20
我需要将类变量转置为列,即
class1 class2
country Number Number
可以在 Shell 或 Python 中执行此操作吗?
我知道可以在 Python 中使用 zip()
完全转置矩阵,但我只想转置 class
列。是否可以在 Python 或 shellscript 中做到这一点?
最佳答案
您想要旋转数据,而不是转置数据:
import pandas
from io import StringIO # python 3
# from StringIO import StringIO # python 2
datafile = StringIO("""\
Country;Class;Number
UK;1;50
Germany;2;30
France;3;50
France;1;20
""")
df = pandas.read_csv(datafile, sep=';')
print(df.pivot(index='Country', columns='Class', values='Number'))
Class 1 2 3
Country
France 20 NaN 50
Germany NaN 30 NaN
UK 50 NaN NaN
关于python - 在Python中将行转置为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27334539/