提取1列中的数值,并将其添加到已解析索引下的新索引中

问题描述 投票:2回答:1

非常感谢您的帮助,我有一个很大的问题,我有如下数据框:

Name | Book | Location 
A    | Mobile| Hai Long St. 123
B    | Sim   | Aha 123/456,78;9

我想分开如下:

Name | Book | Location 
A    | Mobile| 123
B    | Sim   | 123
B    | Sim   | 456
B    | Sim   | 78
B    | Sim   | 9

我怎么能在python中做到这一点,我对这个没有任何想法。谢谢你的支持。

python dataframe split extract numeric
1个回答
0
投票

我会使用extractall来查找Location中的所有数值:

>>> df.Location.str.extractall('(\d+)')
           0
  match     
0 0      123
1 0      123
  1      456
  2       78
  3        9

然后,您可以使用上面extractall输出的索引的第一级将其重新连接到原始数据框中。以下是获取您所需输出的代码:

new_df = (df.drop('Location', axis=1)
          .join(df.Location.str.extractall('(\d+)')
                .reset_index(level=1,drop=True))
          .rename(columns={0:'Location'}))

>>> new_df
  Name    Book Location
0    A  Mobile      123
1    B     Sim      123
1    B     Sim      456
1    B     Sim       78
1    B     Sim        9
© www.soinside.com 2019 - 2024. All rights reserved.