【问题标题】:python pandas partial string matchpython pandas部分字符串匹配
【发布时间】:2017-07-15 18:34:39
【问题描述】:

我创建了一个数据框 df,其中有一列具有以下值:

category
20150115_Holiday_HK_Misc
20150115_Holiday_SG_Misc
20140116_DE_ProductFocus
20140116_UK_ProductFocus

我想创建 3 个新列

category                  |           A              |  B  |       C     
20150115_Holiday_HK_Misc     20150115_Holiday_Misc     HK    Holiday_Misc 
20150115_Holiday_SG_Misc     20150115_Holiday_Misc     SG    Holiday_Misc
20140116_DE_ProductFocus     20140116_ProductFocus     DE    ProductFocus
20140116_UK_ProductFocus     20140116_ProductFocus     UK    ProductFocus

在A列中,我想取出“_HK” - 我想我需要手动编码,但这很好,我有所有国家代码的列表

在 B 列中,就是国家/地区代码

C列,是A列,开头没有日期

我正在尝试这样的事情,但还没有走远。

 df['B'] = np.where([df['category'].str.contains("HK")==True], 'HK', 'Not Specified')

谢谢

【问题讨论】:

  • 我正在考虑一些字符串方法,例如.split()
  • 除了你的字符串不是所有的结构都一样,所以它不能让你准确地到达你想要的位置。

标签: python string pandas match


【解决方案1】:

你可以使用Series.str.extract()方法:

# remove two characters (Country Code) surrounded by '_'
df['A'] = df.category.str.replace(r'_\w{2}_', '_')
# extract two characters (Country Code) surrounded by '_' 
df['B'] = df.category.str.extract(r'_(\w{2})_', expand=False)
df['C'] = df.A.str.extract(r'\d+_(.*)', expand=False)

结果:

In [148]: df
Out[148]:
                   category                      A   B             C
0  20150115_Holiday_HK_Misc  20150115_Holiday_Misc  HK  Holiday_Misc
1  20150115_Holiday_SG_Misc  20150115_Holiday_Misc  SG  Holiday_Misc
2  20140116_DE_ProductFocus  20140116_ProductFocus  DE  ProductFocus
3  20140116_UK_ProductFocus  20140116_ProductFocus  UK  ProductFocus

【讨论】:

  • 对 C 使用列 A.extract 非常聪明。使正则表达式更具可读性。
  • @MaxU 非常感谢! :)
  • 看起来很漂亮:)
【解决方案2】:

你也可以使用正则表达式并应用

import re
df['A'] = df.category.apply(lambda x:re.sub(r'(.*)_(\w\w)_(.*)', r'\1_\3', x))
df['B'] = df.category.apply(lambda x:re.sub(r'(.*)_(\w\w)_(.*)', r'\2', x))
df['C'] = df.A.apply(lambda x:re.sub(r'(\d+)_(.*)', r'\2', x))

结果

                   category                      A   B             C
0  20150115_Holiday_HK_Misc  20150115_Holiday_Misc  HK  Holiday_Misc
1  20150115_Holiday_SG_Misc  20150115_Holiday_Misc  SG  Holiday_Misc
2  20140116_DE_ProductFocus  20140116_ProductFocus  DE  ProductFocus
3  20140116_UK_ProductFocus  20140116_ProductFocus  UK  ProductFocus

【讨论】:

    猜你喜欢
    • 2019-06-14
    • 2016-06-09
    • 1970-01-01
    • 2018-12-01
    • 2012-06-15
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2020-10-01
    相关资源
    最近更新 更多