Python 如何转置 csv 文件中的数据集?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4869189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to transpose a dataset in a csv file?
提问by zr.
For example, i would like to transform:
例如,我想转换:
Name,Time,Score
Dan,68,20
Suse,42,40
Tracy,50,38
Into:
进入:
Name,Dan,Suse,Tracy
Time,68,42,50
Score,20,40,38
EDIT: the original question used the term "transpose" incorrectly.
编辑:原始问题错误地使用了“转置”一词。
采纳答案by Sven Marnach
If the whole file contents fits into memory, you can use
如果整个文件内容适合内存,您可以使用
import csv
from itertools import izip
a = izip(*csv.reader(open("input.csv", "rb")))
csv.writer(open("output.csv", "wb")).writerows(a)
You can basically think of zip()and izip()as transpose operations:
您基本上可以将zip()和izip()视为转置操作:
a = [(1, 2, 3),
(4, 5, 6),
(7, 8, 9)]
zip(*a)
# [(1, 4, 7),
# (2, 5, 8),
# (3, 6, 9)]
izip()avoids the immediate copying of the data, but will basically do the same.
izip()避免立即复制数据,但基本上会这样做。
回答by Elalfer
If linesis the list of your original text than it should be
如果lines是原始文本的列表,则应该是
for i in range(1,len(lines)):
lines[i] = lines[i].split(',')
new_lines = []
for i in range(len(lines[0])):
new_lines.append("%s,%s,%s" % (lines[0][i], lines[1][i], lines[2][i]))
or use csvPython module - http://docs.python.org/library/csv.html
或使用csvPython 模块 - http://docs.python.org/library/csv.html
回答by nosklo
from itertools import izip
from csv import reader, writer
with open('source.csv') as f, open('destination.csv', 'w') as fw:
writer(fw, delimiter=',').writerows(izip(*reader(f, delimiter=',')))
回答by Da Qi
Transfer from input.csvto output.csv. Pandas can also help.
从 转移input.csv到output.csv。熊猫也可以提供帮助。
import pandas as pd
pd.read_csv('input.csv', header=None).T.to_csv('output.csv', header=False, index=False)
回答by Da Qi
The simplest way is:
最简单的方法是:
import numpy as np
import pandas as pd
_mat = pd.read_csv("test.csv")
_mat = _mat[_mat.columns[0:3]].values
_t_mat = np.transpose(_mat)
Result:
结果:
- Input matrix is : [[1 2 3] [4 5 6]]
- the output is: [[1 4] [2 5] [3 6]]
- 输入矩阵为:[[1 2 3] [4 5 6]]
- 输出为:[[1 4] [2 5] [3 6]]
回答by deepak
Read the CSV into pandasdata frame, pandas has build in function for transpose which can be invoked as below.
将 CSV 读入pandas数据框,pandas 内置了转置函数,可以调用如下。
import pandas as pd
csv = pd.read_csv("test.csv", skiprows=1)
# use skiprows if you want to skip headers
df_csv = pd.DataFrame(data=csv)
transposed_csv = df_csv.T
print(transposed_csv)
回答by Joe
Same answer of nosklo (all credits to him), but for python3:
nosklo 的相同答案(全部归功于他),但对于 python3:
from csv import reader, writer
with open('source.csv') as f, open('destination.csv', 'w') as fw:
writer(fw, delimiter=',').writerows(zip(*reader(f, delimiter=',')))

