有没有一种方法可以将包含连接列表的数据框转换为字典?

huangapple go评论57阅读模式
英文:

Is there a way to convert a dataframe containing concatenated list to a dictionary?

问题

我有一个包含连接列表的列的数据框。

A B
Cow ["Sheep","Pig","Bear"]
Monkey ["Frog","Toad","Bird"]

如何将其转换为字典,其中列A是键,列B是值?

英文:

I have a dataframe with a column that contains concatenated lists.

| A        | B                  |
| -------- | --------------     |
| Cow      | ["Sheep","Pig","Bear"]            
| Monkey   | ["Frog","Toad","Bird"]   

How do I convert this to a dictionary where Column A is the key and Column B are the values?

答案1

得分: 1

你可以使用

dictionary = df.set_index('A')['B'].to_dict()

结果为

>>> dictionary
{'cow': ['Sheep', 'Pig', 'Bear'], 'Monkey': ['Frog', 'Toad', 'Bird']}
英文:

You can use

dictionary = df.set_index('A')['B'].to_dict()

The result

>>> dictionary
{'cow': ['Sheep', 'Pig', 'Bear'], 'Monkey': ['Frog', 'Toad', 'Bird']}

答案2

得分: 0

这个解决方案是灵活的,但我不建议在大型数据集上使用。

import pandas as pd

data = [['cow', ['Sheep', 'Pig', 'Bear']], ['Monkey', ['Frog', 'Toad', 'Bird']]]
df = pd.DataFrame(data, columns=['A', 'B'])

def df_toDict(obj, my_dict):
    my_dict[obj['A']] = obj['B']

my_dict = {}
df.T.apply(lambda _ : df_toDict(_, my_dict))

print(my_dict)

通过使用 T,您可以转置数据框,因为 pandas 默认是面向列的。使用 apply 函数遍历列(行.T),并应用一个函数,传入您要填充的字典。

英文:

This solution is flexible, but I wouldn't recommend it on large datasets.

import pandas as pd

data = [['cow', ["Sheep","Pig","Bear"]], ['Monkey', ["Frog","Toad","Bird"]]]

df = pd.DataFrame(data, columns=['A', 'B'])

def df_toDict(obj, my_dict):
    my_dict[obj['A']] = obj['B']

my_dict = {}
df.T.apply(lambda _ : df_toDict(_, my_dict))

print(my_dict)

By using T you transpose the DataFrame since pandas is naturally oriented to columns. Use the apply function to intirate over the columns (rows.T) and apply a function passing in the dictionary you want to populate.

答案3

得分: 0

>>> df.set_index('A')['B'].to_dict()

{'Cow': ['Sheep', 'Pig', 'Bear'],
 'Monkey': ['Frog', 'Toad', 'Bird']}
英文:

You can use:

>>> df.set_index('A')['B'].to_dict()

{'Cow': ['Sheep', 'Pig', 'Bear'],
 'Monkey': ['Frog', 'Toad', 'Bird']}

huangapple
  • 本文由 发表于 2023年2月16日 12:13:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75467787.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定