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

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

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.

  1. | A | B |
  2. | -------- | -------------- |
  3. | Cow | ["Sheep","Pig","Bear"]
  4. | 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

你可以使用

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

结果为

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

You can use

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

The result

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

答案2

得分: 0

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

  1. import pandas as pd
  2. data = [['cow', ['Sheep', 'Pig', 'Bear']], ['Monkey', ['Frog', 'Toad', 'Bird']]]
  3. df = pd.DataFrame(data, columns=['A', 'B'])
  4. def df_toDict(obj, my_dict):
  5. my_dict[obj['A']] = obj['B']
  6. my_dict = {}
  7. df.T.apply(lambda _ : df_toDict(_, my_dict))
  8. print(my_dict)

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

英文:

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

  1. import pandas as pd
  2. data = [['cow', ["Sheep","Pig","Bear"]], ['Monkey', ["Frog","Toad","Bird"]]]
  3. df = pd.DataFrame(data, columns=['A', 'B'])
  4. def df_toDict(obj, my_dict):
  5. my_dict[obj['A']] = obj['B']
  6. my_dict = {}
  7. df.T.apply(lambda _ : df_toDict(_, my_dict))
  8. 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

  1. >>> df.set_index('A')['B'].to_dict()
  2. {'Cow': ['Sheep', 'Pig', 'Bear'],
  3. 'Monkey': ['Frog', 'Toad', 'Bird']}
英文:

You can use:

  1. >>> df.set_index('A')['B'].to_dict()
  2. {'Cow': ['Sheep', 'Pig', 'Bear'],
  3. '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:

确定