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