[英]How to transpose column to row?
我将数据保存在一个文件中:
样品:
City Very poor Poor Fair Good Excellent
Mumbai 0 4 30 58 8
Delhi 5 7 18 39 31
我想将列转置为行:
Mumbai 0 Very poor
Mumbai 4 Poor
Mumbai 30 Fair
Mumbai 58 Good
Mumbai 8 Excellent
.....
.....
python中是否有任何功能可以做到这一点? 我已经在xml中使用xml路径完成了此操作,但我不知道在python中执行的最佳方法。
这是仅使用标准库中的csv
模块的解决方案。
为了方便起见,我们使用csv.DictReader
读取并通过返回的OrderedDict
对象使用标头。
from io import StringIO
import csv
mystr = StringIO("""City VeryPoor Poor Fair Good Excellent
Mumbai 0 4 30 58 8
Delhi 5 7 18 39 31""")
# replace mystr with open('file.csv', 'r')
with mystr as fin:
reader = csv.DictReader(fin, delimiter=' ')
for line in reader:
city = line.popitem(last=False)[1]
for cat, rating in line.items():
print(city, rating, cat)
Mumbai 0 VeryPoor
Mumbai 4 Poor
Mumbai 30 Fair
Mumbai 58 Good
Mumbai 8 Excellent
Delhi 5 VeryPoor
Delhi 7 Poor
Delhi 18 Fair
Delhi 39 Good
Delhi 31 Excellent
请注意,我以较小的方式更改了您的数据: VeryPoor
是类别,而不是Very Poor
VeryPoor
您可能需要在标头中为非标准空格指定特定的处理方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.