[英]Pandas combine two columns with delimiters
我有两列有分隔符:
column1 column2
a,b,c,d e,f,g,h
h,i j,k
l,m,n o,p,q
... ...
我试图将它们分组为 ae、bf、cg、dh、hj、ik 等。
我可以拆分分隔符,但我不知道如何组合这些分隔符,我们将不胜感激。
saved_column_1 = df["column1"].str.split(',', expand=True)
saved_column_2 = df["column2"].str.split(',', expand=True)
使用嵌套列表理解:
df['new'] = [','.join(''.join(x)
for x in list(zip(a.split(','), b.split(','))))
for a, b in zip(df['column1'], df['column2'])]
print (df)
column1 column2 new
0 a,b,c,d e,f,g,h ae,bf,cg,dh
1 h,i j,k hj,ik
2 l,m,n o,p.q lo,mp,nq
如果需要系列:
L = [''.join(x) for a, b in zip(df['column1'], df['column2'])
for x in list(zip(a.split(','),b.split(',')))]
s = pd.Series(L)
print (s)
0 ae
1 bf
2 cg
3 dh
4 hj
5 ik
6 lo
7 mp
8 nq
dtype: object
IIUC,你可以使用:
(df.apply(lambda c: c.str.split('[,.]')) # or split(',') if the '.' is a typo
.explode(list(df.columns))
.agg(''.join, axis=1)
)
output:
0 ae
0 bf
0 cg
0 dh
1 hj
1 ik
2 lo
2 mp
2 nq
dtype: object
对于第二级分组:
(df.apply(lambda c: c.str.split('[,.]'))
.explode(list(df.columns))
.agg(''.join, axis=1)
.groupby(level=0).agg(','.join) # this line is added
)
output:
0 ae,bf,cg,dh
1 hj,ik
2 lo,mp,nq
dtype: object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.