【问题标题】:Add values from one dictionary to another after making operations on those values在对这些值进行操作后将值从一个字典添加到另一个字典
【发布时间】:2019-05-18 14:50:09
【问题描述】:

我有一个熊猫数据框。我想将数据帧按 2 列分组,获取数据帧切片的长度,然后将长度添加到另一个字典,使用键的第一部分,意思是“C”。

我的代码:

df = pd.DataFrame({'C': [20, 20, 20, 20, 10, 10, 10, 30, 30, 30],
                   'C2': [20, 20, 20, 20, 10, 10, 10, 30, 30, 30],
                   'D': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})

df_dictionary = df.groupby(["C", "C2"])

second_dict = dict()

for key, df_values in df_dictionary:
    print(len(df_values.index))

我尝试了以下方法:

for key[0], df_values in df_dictionary.iteritems():
    second_dict.setdefault(key, []).extend(df_values.index)

但它不允许我对 df_values 执行操作。有什么办法可以解决这个问题吗?最后,第二个字典应该有以下值

【问题讨论】:

  • 样本数据的预期输出是什么?

标签: python python-3.x pandas dataframe dictionary


【解决方案1】:

使用GroupBy.size,通过Series.reset_indexdrop=TrueSeries.to_dict 删除第二级:

d = df.groupby(["C", "C2"]).size().reset_index(level=1, drop=True).to_dict()
print (d)
{10: 3, 20: 4, 30: 3}

如果需要索引值:

d1 = (df.groupby(["C", "C2"])
        .apply(lambda x: x.index.tolist())
        .reset_index(level=1, drop=True)
        .to_dict())
print (d1)
{10: [4, 5, 6], 20: [0, 1, 2, 3], 30: [7, 8, 9]}

您的解决方案应该有效:

for key, df_values in df_dictionary:
    second_dict.setdefault(key[0], []).extend(df_values.index)

print (second_dict)
{10: [4, 5, 6], 20: [0, 1, 2, 3], 30: [7, 8, 9]}

【讨论】:

    猜你喜欢
    • 2022-07-10
    • 1970-01-01
    • 2019-06-19
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-25
    • 1970-01-01
    相关资源
    最近更新 更多