python - 字典中的分组数据

标签 python dictionary pandas

我的数据看起来像这样:

object   weight
table     2.3
chair     1.2
chair     1.0
table     1.5
drawer    1.8
table     1.7

我想根据不同类型的对象 对我的数据进行分组。另外,我想知道我有多少个物体以及它们的重量。

例如,我的最终数据应该是这样的:

object     counter     weight
table         3        2.3, 1.5, 1.7
chair         2        1.2, 1.0
drawer        1        1.8

这是我的尝试:

data = pd.read_csv('data.dat', sep = '\s+')

grouped_data = {'object':[],'counter':[], 'weight':[]}
objects = ['table', 'chair', 'drawer']

for item in objects:
    counter = 0
    weight = []
    grouped_objects['object'].append(item)
    for i in range(len(data)):
        if item == data['name'][i]:
            counter += 1
            grouped_data['weight'].append(data['weight'])
            grouped_data['counter'].append(counter)

它没有给我想要的输出。有什么建议吗?

最佳答案

与聚合:

df.groupby("object")["weight"].agg({"counter": "count", "weight": lambda x: ", ".join(x.astype(str))})
Out[57]: 
        counter         weight
object                        
chair         2       1.2, 1.0
drawer        1            1.8
table         3  2.3, 1.5, 1.7

关于python - 字典中的分组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36986482/

相关文章:

python - 为什么 sys.getdefaultencoding() 与 sys.stdout.encoding 不同?这如何破坏 Unicode 字符串?

Python Pyinstaller Matplotlibrc

c# - 可能的 JSON 到 C# 中的字典

dictionary - 在字典中搜索和替换部分匹配项

python - 物体检测 Action

python - mp4 文件中的重复 stsd 条目

python - 如何将字典转换为多级数据框?

python-2.7 - Pandas 从 python 中的字符串列中删除数字

python - Pandas Groupby & Pivot

python - Pandas 选择单独的列