【问题标题】:how to split a column by another column in pandas dataframe如何在熊猫数据框中将一列拆分为另一列
【发布时间】:2019-07-11 08:56:27
【问题描述】:

我正在清理 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.

【问题讨论】:

  • 你试过df.iterrows() 吗?
  • 我试试df.id.str.map(lambda x:x.split(df.eNBID.str)) 不行

标签: python pandas dataframe split data-cleaning


【解决方案1】:

考虑到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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 2019-10-21
      • 2018-12-04
      • 2021-09-10
      • 2017-08-27
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      相关资源
      最近更新 更多