gpt4 book ai didi

Python pandas 有效地删除 UserWarning 和循环

转载 作者:太空宇宙 更新时间:2023-11-03 13:00:49 27 4
gpt4 key购买 nike

假设我有类似这样的代码:

import pandas as pd

df=pd.DataFrame({'Name': [ 'Jay Leno', 'JayLin', 'Jay-Jameson', 'LinLeno', 'Lin Jameson', 'Python Leno', 'Python Lin', 'Python Jameson', 'Lin Jay', 'Python Monte'],
'Class': ['Rat','L','H','L','L','H', 'H','L','L','Circus']})
df['status']=''

pattern1=['^Jay(\s|-)?(Leno|Lin|Jameson)$','^Python(\s|-)?(Jay|Leno|Lin|Jameson|Monte)$','^Lin(\s|-)?(Leno|Jay|Jameson|Monte)$' ]
pattern2=['^Python(\s|-)?(Jay|Leno|Lin|Jameson|Monte)$' ]
pattern3=['^Lin(\s|-)?(Leno|Jay|Jameson|Monte)$' ]

for i in range(len(pattern1)):
df.loc[df.Name.str.contains(pattern1[i]),'status'] = 'A'

for i in range(len(pattern2)):
df.loc[df.Name.str.contains(pattern2[i]),'status'] = 'B'

for i in range(len(pattern3)):
df.loc[df.Name.str.contains(pattern3[i]),'status'] = 'C'

print (df)

打印:

C:\Python33\lib\site-packages\pandas\core\strings.py:184: UserWarning: This pattern has match groups. To actually get the groups, use str.extract.
" groups, use str.extract.", UserWarning)
Class Name status
0 Rat Jay Leno A
1 L JayLin A
2 H Jay-Jameson A
3 L LinLeno C
4 L Lin Jameson C
5 H Python Leno B
6 H Python Lin B
7 L Python Jameson B
8 L Lin Jay C
9 Circus Python Monte B

[10 rows x 3 columns]

我的问题是如何消除错误,有没有一种方法可以用更少的代码更有效地循环?我知道有一种叫做列表理解的东西,但我对如何使用它们感到困惑。

我知道错误可以用

来抑制
pd.options.mode.chained_assignment = None

最佳答案

使用non-capturing parentheses (?:...):

pattern1=['^Jay(?:\s|-)?(?:Leno|Lin|Jameson)$','^Python(?:\s|-)?(?:Jay|Leno|Lin|Jameson|Monte)$','^Lin(?:\s|-)?(?:Leno|Jay|Jameson|Monte)$' ]
pattern2=['^Python(?:\s|-)?(?:Jay|Leno|Lin|Jameson|Monte)$' ]
pattern3=['^Lin(?:\s|-)?(?:Leno|Jay|Jameson|Monte)$' ]

警告来自this code :

    if regex.groups > 0:
warnings.warn("This pattern has match groups. To actually get the"
" groups, use str.extract.", UserWarning)

所以只要没有组,就没有警告。

关于Python pandas 有效地删除 UserWarning 和循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22104466/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com