Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从词汇表创建具有不同类型值的数据框_Python_Pandas_Dataframe_Dictionary - Fatal编程技术网

Python 从词汇表创建具有不同类型值的数据框

Python 从词汇表创建具有不同类型值的数据框,python,pandas,dataframe,dictionary,Python,Pandas,Dataframe,Dictionary,我真的不习惯熊猫,因此如何解决这个问题: 我有一本叫做table的字典,它类似于: table = dict() table[(1, 1)] = [1000, (1.05, 1.02), [Class1(1.05), Class1(1.02)]] table[(2, 3)] = [3400, (1.8, 2.9), [Class1(1.8), Class1(2.9)]] table[(4, 5, 5)] = [2800, (4, 5.2, 5.1), [Class1(4), Class1(5.2

我真的不习惯熊猫,因此如何解决这个问题:

我有一本叫做table的字典,它类似于:

table = dict()
table[(1, 1)] = [1000, (1.05, 1.02), [Class1(1.05), Class1(1.02)]]
table[(2, 3)] = [3400, (1.8, 2.9), [Class1(1.8), Class1(2.9)]]
table[(4, 5, 5)] = [2800, (4, 5.2, 5.1), [Class1(4), Class1(5.2), Class1(5.1)]]
在这个输入布局中,使用了一个名为Class1的自定义类。此类与数据帧无关,因为它将在从字典到数据帧的传输中丢失。我正在查找的输出数据帧只包含3列:key、replacement key和integer,其中key是字典键,replacement key是列表的第二个值,integer是列表的第一个值

Index          key             Replacement key        Integer
1              (1, 1)          (1.05, 1.02)           1000
2              (2, 3)          (1.8, 2.9)             3400
3              (4, 5, 5)       (4, 5.2, 5.1)          2800
当时,我正试图创建一个空的数据帧并逐行填充它。但是,我未能访问和更换每一行

headers = ['Key','Integer', 'Replacement key']
index = range(1, len(table)+1)
df = pd.DataFrame(index=index, columns=headers)
最后,我还想将此数据框导出为.csv格式,以便使用excel打开和自定义

谢谢您的帮助:

试试看:

df = pd.DataFrame.from_dict(table, orient='index').reset_index().iloc[:,:3]
df.columns =['Key','Integer', 'Replacement key']
# swap the column integer and replacement key
df = df[['Key','Replacement key','Integer']]
print(df)

# export .csv
df.to_csv('test.csv')


         Key Replacement key  Integer
0     (1, 1)    (1.05, 1.02)     1000
1     (2, 3)      (1.8, 2.9)     3400
2  (4, 5, 5)   (4, 5.2, 5.1)     2800
说明

from_dict在orient='index'时将字典的键转换为每行的索引

因此,Reset_索引用于释放作为列的键。iloc用于保留前三列,因为您不需要Class1列

df = pd.DataFrame.from_dict(table, orient='index')
print(df)
              0              1                                                  2
(1, 1)     1000   (1.05, 1.02)  [<__main__.Class1 object at 0x7f0f270b6940>, <...
(2, 3)     3400     (1.8, 2.9)  [<__main__.Class1 object at 0x7f0f270b69e8>, <...
(4, 5, 5)  2800  (4, 5.2, 5.1)  [<__main__.Class1 object at 0x7f0f270c19b0>, <...