问题描述
我有一个2D矩阵,包含13行和13列(除第一列之外的标题),在Python中命名为correl
。
该correl
矩阵是从DataFrame
生成的,我希望用多个correl
填充矩阵correlation
。
例如:
correlation=[]
correl=df.corr()
correlation=correlation.append(correl) #correlation is not a DataFrame
我使用correlation=[]
原因是因为我希望用多个相关表填充correlation
性。
这就是我使用append
原因,因为这是一个循环。
现在我想在csv文件中导出这个相关矩阵。 我做:
with open("C:\destinationfolder\file.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(correlation)
我收到此错误:
raise KeyError('no item named %s' % com.pprint_thing(item)) KeyError: u'no item named 0'
为什么? 我的猜测是我没有第一列的标题...是否有更简单的方法将我的相关表导出到csv?
1楼
看起来像 ,所以你可以简单地使用 :
correlation.to_csv("C:\destinationfolder\file.csv")
如果您有DataFrames列表,请更新以回答:
如果您有一个要在csv中创建的DataFrame列表,您有两个选择:
将列表连接成一个更大的框架,并使用
to_csv
:pd.concat(list_of_dataframes).to_csv(...)
迭代每个DataFrame并使用
to_csv
with 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')
请参阅 。