python - 在Python中将行转置为列

标签 python shell csv numpy transpose

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

相关文章:

python - 无法从一些不同深度的链接中解析产品名称

支持非致命故障的 Python 测试框架

linux - 从单个用户导出时在所有 shell 中重复的环境变量

shell - 将文件中的行读入 shell 脚本中的 2 个变量

python - NumPy 的 : read data from CSV having numerals as string

python - 如何检查Python中的字符是否为大写?

python - 逗号从 Windows 中的 Python 3 sys.argv 中消失

mysql - 获取不带表格格式的SQL查询结果

csv - 如何将 Excel 或 CSV 文件加载到 Firebird 中?

powershell - PowerShell Import-Csv问题-为什么我的输出被视为单列而不是CSV?