简体   繁体   English

合并熊猫dataFrame行

[英]Merging Pandas dataFrame rows

I have a Pandas DataFrame which looks like this: 我有一个看起来像这样的Pandas DataFrame:

Time Image_names
0    [a,b,c,d]
0    [a,c,d,e]
0    [c,d,e,f]
1    [e,f,g,h]
1    [f,g,h,i]

What I wish to obtain: All unique image names for a given Time 我希望获得的内容:给定时间的所有唯一图像名称

Time Image_names
0    [a,b,c,d,e]
1    [e,f,g,h,i]

I'm not sure if I have to use groupby or joins. 我不确定是否必须使用groupby或join。

T Ť

You can using set 您可以使用set

s=df.groupby('Time',as_index=False).Image_names.sum()
s.Image_names=list(map(set,s.Image_names))
s
Out[2034]: 
   Time         Image_names
0     0  {b, c, d, a, f, e}
1     1     {g, h, f, i, e}

One way is to use itertools.chain : 一种方法是使用itertools.chain

from itertools import chain
import pandas as pd


df = pd.DataFrame({'Time': [0, 0, 0, 1, 1],
                   'Image_names': [['a', 'b', 'c', 'd'],
                                   ['a', 'c', 'd', 'e'],
                                   ['c', 'd', 'e', 'f'],
                                   ['e', 'f', 'g', 'h'],
                                   ['f', 'g', 'h', 'i']]})

df = df.groupby('Time')['Image_names'].apply(chain.from_iterable).map(set).reset_index()

#    Time         Image_names
# 0     0  {c, a, f, d, e, b}
# 1     1     {g, h, f, e, i}

Explanation 说明

  • Applying chain.from_iterable joins the lists from each group into one large list for each group. 应用chain.from_iterable将每个组的列表加入到每个组的一个大列表中。
  • Mapping set then creates a set for each group. 然后,映射set为每个组创建一个集。
  • reset_index ensures the result is a dataframe with column headers as required. reset_index可确保结果是具有所需列标题的数据帧。

You can use the following: 您可以使用以下内容:

import pandas as pd
import numpy as np

a=pd.DataFrame([[0,['a','b','c','d']],[0,['a','c','d','e']],
                [0,['c','d','e','f']],[1,['e','f','g','h']],
                [1,['f','g','h','i']]],
                columns=['Time','Image_names'])
a.groupby('Time')['Image_names'].sum().apply(np.unique)

#Out[242]: 
#Time
#0    [a, b, c, d, e, f]
#1       [e, f, g, h, i]
#Name: Image_names, dtype: object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM