【发布时间】: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