我有一个数据框,如下所示:
index col1 col2
1 'A' 'B'
300 'A' 'B'
301 'A' 'B'
400 'A' 'B'
510 'A' 'B'
511 'C' 'D'
512 'E' 'F'
1000 'Q' 'P'
1001 'Q' 'R'
这是来自另一个数据帧的切片。我需要对所有具有连续索引的行进行分组,例如300和301,如果值不同,则需要对值进行分组,如下所示:
index col1 col2
1 'A' 'B'
300, 3001 'A' 'B'
400 'A' 'B'
510, 511, 512 ['A', 'C', 'E'] ['B', 'D', 'F']
1000, 1001 'Q' ['P', 'R']
所以在300 and 301
值相同的情况下,我只保留它们,但在510, 511, 512
值不同的情况下,我必须列出它们,并且1000 and 1001
col1的值相同,所以我保留它们,但col2不同,所以我列出了它们
任何帮助都非常感谢,谢谢!!
采用:
#convert index to column if necessary
df = df.reset_index()
#remove duplicates with sets and if length is 1 add scalar
f = lambda x: list(set(x)) if len(set(x)) > 1 else x.iat[0]
#for index column use join with cast to strings
d = {'index': lambda x: ', '.join(x.astype(str)), 'col1':f, 'col2':f }
#create consecutive groups
g = df['index'].astype(str).str[0]
s = g.ne(g.shift()).cumsum()
#aggregtae by fisrt value of `index` column with dictionary
df = df.groupby(s).agg(d).reset_index(drop=True)
print (df)
index col1 col2
0 1 'A' 'B'
1 300, 301 'A' 'B'
2 400 'A' 'B'
3 510, 511, 512 ['C', 'A', 'E'] ['D', 'B', 'F']
4 1000, 1001 'Q' ['R', 'P']
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句