我正在尝试转置相同格式的多个文件,并将它们合并为一个大的CSV文件。我想使用numpy进行移调作为一种非常快速的方式,但它以某种方式跳过了我需要的所有标题。这些是我的文件:
testfile1.csv
time,topic1,topic2,country
2015-10-01,20,30,usa
2015-10-02,25,35,usa
testfile2.csv
time,topic3,topic4,country
2015-10-01,40,50,uk
2015-10-02,45,55,uk
这是我将所有csv文件转置并合并为1个大文件的代码:
from numpy import genfromtxt
import csv
file_list=['testfile1.csv','testfile2.csv']
def transpose_append(csv_file):
my_data = genfromtxt(item, delimiter=',',skip_header=0)
print my_data, "my_data, not transposed"
if i == 0:
transposed_data = my_data.T
print transposed_data, "transposed_data"
for row in transposed_data:
print row, "row from first file"
csv_writer.writerow([row])
else:
transposed_data = my_data.T
for row in transposed_data:
print row, "row from second file"
csv_writer.writerow([row][:1])
with open("combined_transposed_file.csv", 'wb') as outputfile:
csv_writer = csv.writer(outputfile)
for i,item in enumerate(file_list):
transpose_append(item)
outputfile.close()
这是打印的输出。它显示了转置工作,但它缺少我的标题:
[[ nan nan nan nan]
[ nan 20. 30. nan]
[ nan 25. 35. nan]] my_data, not transposed
[[ nan nan nan]
[ nan 20. 25.]
[ nan 30. 35.]
[ nan nan nan]] transposed_data
这是我的预期输出:
,2015-10-01,2015-10-02,country
topic1,20,25,usa
topic2,30,35,usa
topic3,40,45,uk
topic4,50,55,uk
答案 0 :(得分:1)
genfromtxt
中有多种处理标题的方法。默认设置是将它们视为数据的一部分:
In [6]: txt="""time,topic1,topic2,country
...: 2015-10-01,20,30,usa
...: 2015-10-02,25,35,usa"""
In [7]: data=np.genfromtxt(txt.splitlines(),delimiter=',',skip_header=0)
In [8]: data
Out[8]:
array([[ nan, nan, nan, nan],
[ nan, 20., 30., nan],
[ nan, 25., 35., nan]])
但由于默认dtype为float,因此字符串全部显示为nan
。
您可以将它们视为标题 - 结果是结构化数组。标题现在显示在data.dtype.names
列表中。
In [9]: data=np.genfromtxt(txt.splitlines(),delimiter=',',names=True)
In [10]: data
Out[10]:
array([(nan, 20.0, 30.0, nan), (nan, 25.0, 35.0, nan)],
dtype=[('time', '<f8'), ('topic1', '<f8'), ('topic2', '<f8'), ('country', '<f8')])
使用dtype=None
,您可以选择dtype。根据第1行中的字符串,它将所有内容加载为S10
。
In [11]: data=np.genfromtxt(txt.splitlines(),delimiter=',',dtype=None)
In [12]: data
Out[12]:
array([['time', 'topic1', 'topic2', 'country'],
['2015-10-01', '20', '30', 'usa'],
['2015-10-02', '25', '35', 'usa']],
dtype='|S10')
此矩阵可以转置,打印或写入csv文件:
In [13]: data.T
Out[13]:
array([['time', '2015-10-01', '2015-10-02'],
['topic1', '20', '25'],
['topic2', '30', '35'],
['country', 'usa', 'usa']],
dtype='|S10')
由于我使用genfromtxt
加载,我可以使用savetxt
进行保存:
In [26]: with open('test.txt','w') as f:
np.savetxt(f, data.T, delimiter=',', fmt='%12s')
np.savetxt(f, data.T, delimiter=';', fmt='%10s') # simulate a 2nd array
....:
In [27]: cat test.txt
time, 2015-10-01, 2015-10-02
topic1, 20, 25
topic2, 30, 35
country, usa, usa
time;2015-10-01;2015-10-02
topic1; 20; 25
topic2; 30; 35
country; usa; usa