pandas Python:在csv中导出矩阵
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/22412508/
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
Python: Export a matrix in csv
提问by Plug4
I have a 2D matrix with 13 rows and 13 columns (with headers except for the first column) named correlin Python. This correlmatrix was generated from a DataFrameand I wish to populate a matrix correlationwith multiple correl. For example: 
我有一个 2D 矩阵,有 13 行和 13 列(除了第一列之外还有标题)correl,用 Python命名。这个correl矩阵是从 a 生成的DataFrame,我希望correlation用多个correl. 例如:
correlation=[]
correl=df.corr()
correlation=correlation.append(correl) #correlation is not a DataFrame
The reason why I use the correlation=[]it is because I wish to populate the correlationwith multiple correlation tables. That is why I use the appendsince this is in a loop.  
我使用correlation=[]它的原因是因为我希望correlation用多个相关表填充它。这就是我使用 的原因,append因为这是在循环中。  
Now I wish to export this correlation matrix in a csv file. I do:
现在我希望将此相关矩阵导出到 csv 文件中。我愿意:
with open("C:\destinationfolder\file.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(correlation)
I get this error:
我收到此错误:
raise KeyError('no item named %s' % com.pprint_thing(item))
KeyError: u'no item named 0'
raise KeyError('no item named %s' % com.pprint_thing(item))
KeyError: u'no item named 0'
Why? My guess is that I don't have a header for the first column... is there an easier way to export my correlation table to csv?
为什么?我的猜测是我没有第一列的标题......有没有更简单的方法将我的相关表导出到 csv?
回答by Andy Hayden
It looks like correlationis a DataFrame too, so you can simply use to_csv:
它看起来correlation也是一个 DataFrame,所以你可以简单地使用to_csv:
correlation.to_csv("C:\destinationfolder\file.csv")
Update to answer if you have a list of DataFrames:
如果您有数据帧列表,请更新回答:
If you have a list of DataFrames which you want to make into a csv, you have two options:
如果您有要制作成 csv 的 DataFrame 列表,您有两个选择:
- concat the list into one larger frame, and use - to_csv:- pd.concat(list_of_dataframes).to_csv(...)
- iterate over each DataFrame and use - to_csvwith append (- mode='a'). Something like:- list_of_dataframes[0].to_csv(...) # write first, using headers.. assumes list isn't empty! for df in list_of_dataframes[1:]: df.to_csv(..., header=False, mode='a')
- 将列表连接到一个更大的框架中,并使用 - to_csv:- pd.concat(list_of_dataframes).to_csv(...)
- 迭代每个 DataFrame 并 - to_csv与 append (- mode='a') 一起使用。就像是:- list_of_dataframes[0].to_csv(...) # write first, using headers.. assumes list isn't empty! for df in list_of_dataframes[1:]: df.to_csv(..., header=False, mode='a')

