stackoverflow python笔记1,按条件合并dataframe中字符

Question:

I have the following dataframe

first_char second_char type

1          a           b  1/1
2          a           b  0/1
3          a           b  0/1
4          c           d  1/1
5          c           d  0/1
6          c           d  0/0

I would like to combine these columns into one as such:

1       bb
2       ab
3       ab
4       dd
5       cd
6       cc

Answer 1

ind = df['type'].str.split('/', expand=True).astype(int).to_numpy()
arr2 = df[['first_char','second_char']].to_numpy()    

df['new'] = arr2[np.arange(ind.shape[0])[:,None], ind].sum(1)
print (df)
  first_char second_char type new
1          a           b  1/1  bb
2          a           b  0/1  ab
3          a           b  0/1  ab
4          c           d  1/1  dd
5          c           d  0/1  cd
6          c           d  0/0  cc

Answer 2

s = df["type"].str.split("/", expand=True).astype(int)

df["new"] = np.take_along_axis(df[["first_char","second_char"]].to_numpy(),s.to_numpy(), axis=1).sum(1)

print (df)

  first_char second_char type new
1          a           b  1/1  bb
2          a           b  0/1  ab
3          a           b  0/1  ab
4          c           d  1/1  dd
5          c           d  0/1  cd
6          c           d  0/0  cc

Answer 3

df.apply(lambda x: ''.join([(x['first_char']+x['second_char'])[int(number)] for number in x['type'].split('/')]),axis=1)

1    bb
2    ab
3    ab
4    dd
5    cd
6    cc
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值