【问题标题】:How to add a value inside an numpy array to a python dictionary如何将numpy数组中的值添加到python字典
【发布时间】:2021-03-11 13:41:54
【问题描述】:

我正在尝试遍历 pandas 数据框的列(由 1 和 0 组成)到 groupby 并对另一列求和,然后将 groupby 列名称作为键添加到空字典中,并将总和值作为值。但是我当前的代码添加了一个数组作为值而不是实际值。下面是一些示例代码。

import pandas
sample_dict = {'flag1':[0,1,1,1,1,0],
               'flag2':[1,1,1,0,0,1],
               'flag3':[0,0,0,0,0,1],
               'flag4':[1,1,1,1,0,0],
               'flag5':[1,0,1,0,1,0],
               'dollars':[100,200,300,400,500,600]}
sample_df = pd.DataFrame(sample_dict)

ecols = sample_df.columns[:5]
rate = .46
empty_dict = {}
for i in ecols:
    df= sample_df[sample_df[i] == 1]
    yield1 = df.groupby(i)['dollars'].sum().values*rate
    empty_dict[i] = yield1
    
empty_dict

该代码产生以下输出:

Out[223]: 
{'flag1': array([644.]),
 'flag2': array([552.]),
 'flag3': array([276.]),
 'flag4': array([460.]),
 'flag5': array([414.])}

我只想将实际整数作为值而不是数组。

【问题讨论】:

标签: python dictionary for-loop


【解决方案1】:

你总是得到一个由一个元素组成的数组:只取它的第一个元素(如果有的话):

...
empty_dict[i] = yield1[0] if len(yield) >=1 else np.nan
...

【讨论】:

  • 谢谢,但我知道了:Traceback (most recent call last): File "<ipython-input-232-949311df9ecd>", line 9, in <module> edit_dict[i] = prem[0] IndexError: index 0 is out of bounds for axis 0 with size 0
  • @Jordan 你的原始代码可以给出空数组吗?
  • 是的,它可以有一个空值。
  • 谢谢@SergeBallesta
猜你喜欢
  • 2018-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 2016-01-23
  • 1970-01-01
  • 2017-09-30
相关资源
最近更新 更多