Python/Pandas:如何处理满足特定条件的数据列

2024-10-04 09:22:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我今天有一个谎言

userlabel|country
SZ5GZTD_[56][13631808]|russia
YZ5GZTC-3_[51][13680735]|uk
XZ5GZTA_12-[51][13574893]|usa
testYZ5GZWC_11-[51][13632101]|cuba

我使用pandas读取此csv,我想添加一个新列ci,其值来自userlabel,并且必须满足以下条件:

  1. 将值转换为小写
  2. 以“yz”或“testyz”开头

代码如下所示:

(df['userlabel'].str.lower()).str.extract(r"(test)?([a-z]+).*", expand=True)[1]

当它匹配时,ci是第一个“-or u”和第二个“-or”之间的数字

伪代码如下所示:

ci = (userlabel,r'.*(\_|\-)(\d+)(\_|\-).*',2)

最后,结果是这样的

userlabel                      ci country
SZ5GZTD_[56][13631808]            russia
YZ5GZTC-3_[51][13680735]       3  uk
XZ5GZTA_12-[51][13574893]         usa
testYZ5GZWC_11-[51][13632101]  11 cuba

Tags: or代码cicountryukstrcubausa
2条回答

你可以用

import pandas as pd
df = pd.DataFrame({'userlabel':['SZ5GZTD_[56][13631808]','YZ5GZTC-3_[51][13680735]','XZ5GZTA_12-[51][13574893]','testYZ5GZWC_11-[51][13632101]'], 'country':['russia','uk','usa','cuba']})
df['ci'] = df['userlabel'].str.extract(r"(?i)^(?:yz|testyz)[^_-]*[_-](\d+)[-_]", expand=True)
>>> df['ci']
0    NaN
1      3
2    NaN
3     11
Name: ci, dtype: object
# To rearrange columns, add the following line:
df = df[['userlabel', 'ci', 'country']]
>>> df
                       userlabel   ci country
0         SZ5GZTD_[56][13631808]  NaN  russia
1       YZ5GZTC-3_[51][13680735]    3      uk
2      XZ5GZTA_12-[51][13574893]  NaN     usa
3  testYZ5GZWC_11-[51][13632101]   11    cuba

请参阅regex demo

正则表达式详细信息:

  • (?i)-使模式不区分大小写(无需使用str.lower()
  • ^-字符串的开头
  • (?:yz|testyz)-与yztestyz匹配的非捕获组
  • [^_-]*-除_-之外的零个或多个字符
  • [_-]-第一个{}或{}
  • (\d+)-group1(由于Series.str.extract只返回这个捕获的子字符串,所以它需要一个捕获组):一个或多个数字
  • [-_]-a-_
import re

def get_val(s):
    l = re.findall(r'^(YZ|testYZ).*[_-](\d+)[_-].*', s)
    return  None if(len(l) == 0) else l[0][1]

df['ci'] = df['userlabel'].apply(lambda x: get_val(x))
df = df[['userlabel', 'ci', 'country']]
userlabel                         ci    country
0   SZ5GZTD_[56][13631808]        None  russia
1   YZ5GZTC-3_[51][13680735]      3     uk
2   XZ5GZTA_12-[51][13574893]     None  usa
3   testYZ5GZWC_11-[51][13632101] 11    cuba

相关问题 更多 >