[英]Writing a dict with keys and dataframes to an excel sheet using python
[英]Writing a dict of large dataframes to excel
我正在創建字典,其中字典鍵是字符串,值是大熊貓數據幀。 我想將這些字典寫入 excel 文件,但我遇到的問題是,當 python 將數據幀寫入 csv 時,它會切掉部分。 代碼:
import pandas as pd
import numpy as np
def create_random_df():
return(pd.DataFrame(np.random.randint(0,100,size=(70,26)),columns=list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')))
dic={'key1': create_random_df() , 'key2': create_random_df()}
with open('test.csv', 'w') as f:
for key in dic.keys():
f.write("%s,%s\n"%(key,dic[key]))
除了以下內容之外,這種輸出格式是我想要的:
ABCDEFGHI ... RSTUVWXYZ
然后索引和數據框元素都在 A 列中。即單元格 A2:A4 是
0 55 96 60 47 11 3 2 69 50 ... 3 23 26 3 15 53 78 95 49
1 72 48 12 25 32 57 11 84 5 ... 11 43 56 0 68 55 95 64 84
2 80 56 78 58 79 72 67 97 58 ... 84 34 18 21 71 20 72 36 37
我希望將數據幀完整地寫入 csv,顯然是離散單元格中的值
你可以試試:
dic={'key1': create_random_df() , 'key2': create_random_df()}
with open('test.csv', 'w') as f:
for key in dic.keys():
df = dic[key]
df.insert(0,'Key', pd.Series([key]))
df.Key = df.Key.fillna('')
f.write(df.to_csv(index=False))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.