将数据帧转换为字典

时间:2018-12-27 08:58:31

标签: python-3.x dictionary data-structures

我有一个包含三列的数据框,其中包含220个数据点。现在,我需要使一列成为键,另一列成为值,然后删除第三列。我该怎么办?

我已经通过抓取Wikipedia来创建数据框,以创建关键字搜索。现在,我需要创建一个包含其中的术语的索引,对于这些术语而言,字典是最有效的。如何从数据框中创建字典,其中键中的一列为另一列?

2 个答案:

答案 0 :(得分:0)

由于您未提供实际数据,因此我使用了具有3列3行的示例数据框。您可以将其替换为数据和列名。

我已经使用iterrows()进行循环,遍历每一行。

代码:

import pandas as pd

df = pd.DataFrame (
    {'Alphabet': ['A', 'B','C'] ,
     'Number': [1,2,3],
     'To_Remove': [10, 15, 8]})

sample_dictionary = {}


for index,row in df.iterrows():
    sample_dictionary[row['Alphabet']] = row['Number']

print(sample_dictionary)

输出:

{'A': 1, 'B': 2, 'C': 3}

答案 1 :(得分:0)

您可以使用熊猫功能, pd.Dataframe.to_dict

文档:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html

示例

import pandas as pd

# Original dataframe
df = pd.DataFrame({'col1': [1, 2, 3],
                  'col2': [0.5, 0.75, 1.0],
                   'col3':[0.1, 0.9, 1.9]},
                  index=['a', 'b', 'c'])

# To dictonary
dictionary = df.to_dict(df)