【问题标题】:Pandas split column in several columns throug string replacement or regexPandas 通过字符串替换或正则表达式将列拆分为几列
【发布时间】:2020-02-03 20:13:48
【问题描述】:

我的数据框中有一个“列”,在最佳条件下,它看起来像这样:

Client: Stack Overflow   Order Num: 123456  Account From: 3656645654   Account to: 546546578

我想将此列拆分为几列,例如:

'Client','Order Num', 'Account From','Account to'

但在某些情况下,我在列中没有客户、订单号和帐户

我是这样做的:

for x in len(df.columns):
   if 'Client' in df.loc[x,'Columnn']:
      df.loc[x,'Client'] = str(df.loc[x,'Column']).split('Client: ')[1]
      if 'Order Num' in df.loc[x,'Client']:
         df.loc[x,'Client'] = str(df.loc[x,'Client']).split('Order Num: ')[0]
      if 'Account From' in df.loc[x,'Client']:
         df.loc[x,'Client'] = str(df.loc[x,'Client']).split('Account From: ')[0]
      if 'Account to' in df.loc[x,'Client']:
         df.loc[x,'Client'] = str(df.loc[x,'Client']).split('Account to: ')[0]
   else:
      df.loc[x,'Client'] = ''

对于我要创建的所有列,依此类推。

这部分脚本将近40行,速度很慢。

您有更“夸张”的解决方案吗?

【问题讨论】:

    标签: python pandas split multiple-columns


    【解决方案1】:

    尝试使用字符串访问器 .strextract 以及使用正则表达式的命名组:

    df['col1'].str.extract('Client: (?P<Client>.*) Order Num: (?P<OrderNum>.*) Account From: (?P<AccountFrom>.*) Account to: (?P<AccountTo>.*)')
    

    输出:

                 Client OrderNum   AccountFrom  AccountTo
    0  Stack Overflow    123456   3656645654    546546578
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 2018-06-02
      相关资源
      最近更新 更多