我的数据看起来像这样:
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/