英文:
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']}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论