繁体   English   中英

如何在熊猫数据框中用另一列拆分一列

[英]how to split a column by another column in pandas dataframe

我正在清理pandas数据框中的数据,我想将一列与另一列分开。

我想按“ eNBID”列拆分“ id”列,但不知道如何拆分

import pandas as pd

id_list = ['4600375067649','4600375077246','460037495681','460037495694']
eNBID_list = ['750676','750772','749568','749569']
df=pd.DataFrame({'id':id_list,'eNBID':eNBID_list})

df.head()

id                  eNBID
4600375067649       750676
4600375077246       750772
460037495681        749568
460037495694        749569

What I want:

df.head()

id                     eNBID
460-03-750676-49       750676
460-03-750772-46       750772
460-03-749568-1        749568
460-03-749569-4        749569

#column 'eNBID' is the third part of column 'id', the item length in column 'eNBID' is 6 or 7.

考虑到46003对于所有ID都将保持不变

df['id'] = df.apply(lambda x: '-'.join([i[:3]+'-'+i[3:] if '460' in i else i for i in list(re.findall('(\w*)'+'('+x.eNBID+')'+'(\w*)',x.id)[0])]), axis=1)

产量

                 id   eNBID
0  460-03-750676-49  750676
1  460-03-750772-46  750772
2   460-03-749568-1  749568
3   460-03-749569-4  749569

在第3、5、11位之后考虑“-”:

df['id'] = df['id'].apply(lambda s: s[:3] + '-' + s[3:5] + '-' + s[5:11] + '-' + s[11:])

暂无
暂无

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

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