将具有相同行标签但前缀不同的值组合在一起-pandas

时间:2019-05-06 01:14:28

标签: python pandas

df = pd.DataFrame({'x':['az_LC','bz_LC','ZG','az_KJ','bz_KJ'],'y':[1,2,3,4,5]})

我想将y中的值组合为相同的字母组合(不带前缀)。例如,有LC和前缀azbz的两个实例。我想将y的{​​{1}}值合并到一个列表中。问题是我还有其他没有前缀的字母组合(例如LC)。这是期望的输出

ZG

编辑:我的某些字母组合包含下划线,但它们仍然是唯一的

   x    y
0  LC  [1,2]
1  ZG  [3]
2  KJ  [4,5]

所需的输出

df = pd.DataFrame({'x':['az_LC','bz_LC','ZG','az_KJ','bz_KJ','U_FT'],'y':[1,2,3,4,5,6]})

1 个答案:

答案 0 :(得分:1)

IIUC str.splitpd.Series.groupby

df.y.groupby(df.x.str.split('_').str[-1]).apply(list).reset_index()
Out[103]: 
    x       y
0  KJ  [4, 5]
1  LC  [1, 2]
2  ZG     [3]

更新

df1=df.loc[df.x.str.startswith(('az','bz'))]
df2=df.drop(df1.index)
s1=df1.y.groupby(df1.x.str.split('_',1).str[-1]).apply(list)
s2=df2.y.groupby(df2.x).apply(list)
df=pd.concat([s1,s2])
df
Out[113]: 
x
KJ      [4, 5]
LC      [1, 2]
U_FT       [6]
ZG         [3]
Name: y, dtype: object
相关问题