将数据框行汇总到字典中

时间:2018-11-22 17:46:28

标签: python pandas

我有一个pandas DataFrame对象,其中每一行代表一个图像中的一个对象。

可能的行的一个示例是:

{'img_filename': 'img1.txt', 'img_size':'20', 'obj_size':'5', 'obj_type':'car'}

我想聚合属于同一图像的所有对象,并得到行类似的东西:

{'img_filename': 'img1.txt', 'img_size':'20', 'obj': [{'obj_size':'5', 'obj_type':'car'}, {{'obj_size':'6', 'obj_type':'bus'}}]}

也就是说,第三列是包含每个组数据的列的列表。

我该怎么做?

编辑:

请考虑以下示例。

import pandas as pd
df1 = pd.DataFrame([
{'img_filename': 'img1.txt', 'img_size':'20', 'obj_size':'5', 'obj_type':'car'}, 
{'img_filename': 'img1.txt', 'img_size':'20', 'obj_size':'6', 'obj_type':'bus'}, 
{'img_filename': 'img2.txt', 'img_size':'25', 'obj_size':'4', 'obj_type':'car'}
])

df2 = pd.DataFrame([
{'img_filename': 'img1.txt', 'img_size':'20', 'obj': [{'obj_size':'5', 'obj_type':'car'}, {'obj_size':'6', 'obj_type':'bus'}]},
{'img_filename': 'img2.txt', 'img_size':'25', 'obj': [{'obj_size':'4', 'obj_type':'car'}]}
])

我想将df1变成df2

2 个答案:

答案 0 :(得分:1)

使用to_dict

的一种方法
df2 = df1.groupby('img_filename')['obj_size','obj_type'].apply(lambda x: x.to_dict('records'))
df2 = df2.reset_index(name='obj')

# Assuming you have multiple same img files with different sizes then I'm choosing first.
# If this not the case then groupby directly and reset index.
#df1.groupby('img_filename, 'img_size')['obj_size','obj_type'].apply(lambda x: x.to_dict('records'))

df2['img_size'] = df1.groupby('img_filename')['img_size'].first().values

print (df2)

  img_filename                                                obj img_size
0     img1.txt  [{'obj_size': '5', 'obj_type': 'car'}, {'obj_s...       20
1     img2.txt             [{'obj_size': '4', 'obj_type': 'car'}]       25

答案 1 :(得分:1)

一个衬里。

假设您有相同的img_filename和不同的img_size,并且您想join的值。 例如:

  img_filename img_size obj_size obj_type
0     img1.txt       20        5      car
1     img1.txt       22        6      bus
2     img2.txt       25        4      car

# if you want to join the img_size of img1.txt like 20, 22
df2 = df1.groupby("img_filename")["img_size", "obj_size", "obj_type"].apply(lambda x: pd.Series({"obj": x[["obj_size", "obj_type"]].to_json(orient="records"), "img_size": ','.join(x["img_size"])})).reset_index()

输出:

  img_filename                                                obj img_size
0     img1.txt  [{"obj_size":"5","obj_type":"car"},{"obj_size"...    20,22
1     img2.txt                [{"obj_size":"4","obj_type":"car"}]       25

考虑第一个值

#if you want to consider only first value i.e. 20
df2 = df1.groupby("img_filename")["img_size", "obj_size", "obj_type"].apply(lambda x: pd.Series({"obj": x[["obj_size", "obj_type"]].to_json(orient="records"), "img_size": x["img_size"].iloc[0]})).reset_index()

输出:

  img_filename                                                obj img_size
0     img1.txt  [{"obj_size":"5","obj_type":"car"},{"obj_size"...       20
1     img2.txt                [{"obj_size":"4","obj_type":"car"}]       25