【问题标题】:to_dict() creates brackets around valuesto_dict() 在值周围创建括号
【发布时间】:2018-09-17 22:11:54
【问题描述】:

我正在尝试从我的 pandas DataFrame 创建默认字典,但 to_dict() 方法会在我要写入的列的值周围创建不需要的方括号。示例代码如下:

# Create DF
my_df = pd.DataFrame({'numbers': (1, 2, 3, 4, 5), 'letters': ('a', 'b', 'c', 'd', 'e')})

# Create dictionary from the DF
my_dict = my_df.set_index('numbers').T.to_dict('list')

# Create collections dictionary
my_collections_dict = collections.defaultdict(int, my_dict)

结果:

defaultdict(int, {1: ['a'], 2: ['b'], 3: ['c'], 4: ['d'], 5: ['e']})

我想要的是:

defaultdict(int, {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'})

如何获取“纯”列值?

【问题讨论】:

  • 您将dict 传递给defaultdict 构造函数,因此它将返回等效的defaultdict。

标签: python pandas dictionary


【解决方案1】:

你不需要转置你的框架,你可以选择你的列然后做:

my_dict = my_df.set_index('numbers')['letters'].to_dict()

如果您想在字典中使用多个列,则需要多一行,但您可以使用:

my_dict = my_df.set_index('numbers').to_dict(orient='index')
my_dict = {k: list(v.values()) for k, v in my_dict.items()}

【讨论】:

  • 谢谢!这甚至以更简单和更快的方式解决了我的问题。如果我有不止一列,它将如何工作?例如:pd.DataFrame({'numbers': (1, 2, 3, 4, 5), 'letters': ('a', 'b', 'c', 'd', 'e'), 'other_letters': ('f', 'g', 'h', 'j', ''k)})
  • @IamNik 您希望多列的输出是什么?
  • 我想从我的问题中获得类似的结果:defaultdict(int, {1: ['a', 'f'], 2: ['b', 'g'], ...
【解决方案2】:

这是因为您指定了to_dict('list') -> 这样条目将作为列表返回(这就是它们显示在[] 中的原因。

尝试改用records

# Create DF
my_df = pd.DataFrame({'numbers': (1, 2, 3, 4, 5), 'letters': ('a', 'b', 'c', 'd', 'e')})

# Create dictionary from the DF
my_dict = my_df.set_index('numbers').T.to_dict('records')

# Create collections dictionary
my_collections_dict = collections.defaultdict(int, my_dict)

第二行的输出:

[{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}]

【讨论】:

  • 我不知道为什么,但我收到以下错误ValueError: dictionary update sequence element #0 has length 5; 2 is required
  • 如果你跳过换位(第二行中的 T)会发生什么?
  • 我不认为它的转置 - my_dict id 成功创建。问题出在defaultdict() - 它不想从my_dict 创建默认字典。好的部分是 - my_dict 现在确实没有括号:)
猜你喜欢
  • 1970-01-01
  • 2020-05-28
  • 1970-01-01
  • 2016-06-04
  • 2014-05-31
  • 1970-01-01
  • 2021-07-24
  • 1970-01-01
  • 2020-10-26
相关资源
最近更新 更多