简体   繁体   English

如何使用熊猫将dict(具有多个列表的键)转储到csv?

[英]How to dump dict(key with multiple list) to csv using pandas?

I have dictionary like 我有像这样的字典

my_dict={
"A": [["value-1", "value-2"], [1, 2]],
"B": [["price-1", "price-2"], [1,2]]
}

I want to dump this dictionary with pandas into csv file 我想将此字典和熊猫一起dumpcsv文件中

import pandas as pd
df = pd.DataFrame.from_dict(data=my_dict, orient='index')
df.to_csv("data/mydict_11sept.csv", sep=',')

output: 输出:

           A           |       B
________________________________________________    
["value-1", "value-2"] | ["price-1", "price-2"]
       [1, 2]          |     [1,2]

expected Output: 预期输出:

    A       |    B
-----------------------
value-1 | 1 | price-1 | 1
value-2 | 2 | price-2 | 2

Updated: output of my file is given and expected file format is given 更新:给出了我文件的输出,给出了预期的文件格式

在此处输入图片说明

Use preprocessing first in dict comprehension with enumerate : 首先在带有enumerate dict理解中使用预处理:

d = {f'{k}_{i}': x for k, v in my_dict.items() for i, x in enumerate(v)}
df = pd.DataFrame(d)
print (df)
       A_0  A_1      B_0  B_1
0  value-1    1  price-1    1
1  value-2    2  price-2    2

EDIT: 编辑:

d = {k:list(zip(*v)) for k, v in my_dict.items()}
df = pd.DataFrame(data=d)
print (df)
              A             B
0  (value-1, 1)  (price-1, 1)
1  (value-2, 2)  (price-2, 2)

Or: 要么:

d = {k:[', '.join(str(y) for y in x) for x in zip(*v)] for k, v in my_dict.items()}
df = pd.DataFrame(data=d)
print (df)
            A           B
0  value-1, 1  price-1, 1
1  value-2, 2  price-2, 2

EDIT1: Here is possible create MultiIndex in columns: EDIT1:可以在列中创建MultiIndex

d = {(k, i) : x for k, v in my_dict.items() for i, x in enumerate(v)}
df = pd.DataFrame(d)
print (df)
         A           B   
         0  1        0  1
0  value-1  1  price-1  1
1  value-2  2  price-2  2

And if necessary, remove second level, but not recommended, because problem selectin by columns names only one column: 并且如有必要,请删除第二级,但不建议这样做,因为按列进行的问题选择仅会命名一列:

df.columns = df.columns.droplevel(1)
print (df)
         A  A        B  B
0  value-1  1  price-1  1
1  value-2  2  price-2  2

print (df['A'])
         A  A
0  value-1  1
1  value-2  2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM