使用Pandas对多个CSV文件进行索引?
我有一堆CSV文件(比如"file1", "file2", ..."
),这些文件里有两列数据,但没有列名。我想给它们加上列名,然后把它们放进一个DataFrame
里,这个DataFrame
的索引是文件名,接着再用列名来索引。例如,我试过这样做:
import pandas
mydict = {}
labels = ["col1", "col2"]
for myfile in ["file1", "file2"]:
my_df = pandas.read_table(myfile, names=labels)
# build dictionary of dataframe records
mydict[myfile] = my_df
test = pandas.DataFrame(mydict)
这样做之后,生成了一个名为test的DataFrame
,它的索引是"myfile1", "myfile2"...
,但是我希望每个文件名下面也能用"col1"
和"col2"
来索引。我的问题是:
我该怎么做才能让第一个索引是文件名,第二个索引是我给的列名(保存在
labels
这个变量里)?这样我就可以写:test["myfile1"]["col1"]
现在,test["myfile1"]
只给我一系列记录。
另外,我该怎么重新索引,让第一个索引是每个文件的列名,第二个索引是文件名?这样我就可以写:
test["col1"]["myfile1"]
或者我可以用print test["col1"]
来查看"col1"
在myfile1, myfile2
等文件中的值。
1 个回答
6
如果你正在使用 pandas 版本大于等于 0.7.0(目前这个版本只在 GitHub 上可以找到,不过我很快就会发布正式版本!),你可以把你的多个数据框(DataFrames)合并在一起:
http://pandas.sourceforge.net/merging.html#more-concatenating-with-group-keys
In [6]: data
Out[6]:
{'file1.csv': A B
0 1.0914 -1.3538
1 0.5775 -0.2392
2 -0.2157 -0.2253
3 -2.4924 1.0896
4 0.6910 0.8992
5 -1.6196 0.3009
6 -1.5500 0.1360
7 -0.2156 0.4530
8 1.7018 1.1169
9 -1.7378 -0.3373,
'file2.csv': A B
0 -0.4948 -0.15551
1 0.6987 0.85838
2 -1.3949 0.25995
3 1.5314 1.25364
4 1.8582 0.09912
5 -1.1717 -0.21276
6 -0.2603 -1.78605
7 -3.3247 1.26865
8 0.7741 -2.25362
9 -0.6956 1.08774}
In [10]: cdf = concat(data, axis=1)
In [11]: cdf
O ut[11]:
file1.csv file2.csv
A B A B
0 1.0914 -1.3538 -0.4948 -0.15551
1 0.5775 -0.2392 0.6987 0.85838
2 -0.2157 -0.2253 -1.3949 0.25995
3 -2.4924 1.0896 1.5314 1.25364
4 0.6910 0.8992 1.8582 0.09912
5 -1.6196 0.3009 -1.1717 -0.21276
6 -1.5500 0.1360 -0.2603 -1.78605
7 -0.2156 0.4530 -3.3247 1.26865
8 1.7018 1.1169 0.7741 -2.25362
9 -1.7378 -0.3373 -0.6956 1.08774
然后,如果你想要改变列的顺序,可以这样做:
In [14]: cdf.swaplevel(0, 1, axis=1)
Out[14]:
A B A B
file1.csv file1.csv file2.csv file2.csv
0 1.0914 -1.3538 -0.4948 -0.15551
1 0.5775 -0.2392 0.6987 0.85838
2 -0.2157 -0.2253 -1.3949 0.25995
3 -2.4924 1.0896 1.5314 1.25364
4 0.6910 0.8992 1.8582 0.09912
5 -1.6196 0.3009 -1.1717 -0.21276
6 -1.5500 0.1360 -0.2603 -1.78605
7 -0.2156 0.4530 -3.3247 1.26865
8 1.7018 1.1169 0.7741 -2.25362
9 -1.7378 -0.3373 -0.6956 1.08774
另外,你也可以使用一个叫做 Panel 的东西,这样可能会更简单:
In [16]: p = Panel(data)
In [17]: p
Out[17]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 10 (major) x 2 (minor)
Items: file1.csv to file2.csv
Major axis: 0 to 9
Minor axis: A to B
In [18]: p = p.swapaxes(0, 2)
In [19]: p
Out[19]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 10 (major) x 2 (minor)
Items: A to B
Major axis: 0 to 9
Minor axis: file1.csv to file2.csv
In [20]: p['A']
Out[20]:
file1.csv file2.csv
0 1.0914 -0.4948
1 0.5775 0.6987
2 -0.2157 -1.3949
3 -2.4924 1.5314
4 0.6910 1.8582
5 -1.6196 -1.1717
6 -1.5500 -0.2603
7 -0.2156 -3.3247
8 1.7018 0.7741
9 -1.7378 -0.6956