Python pandas有效地删除UserWarning和循环 [英] Python pandas Removing UserWarning and looping efficiently
本文介绍了Python pandas有效地删除UserWarning和循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我的代码与此类似:
Lets say I have code similar to this:
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]
我的问题是如何删除错误,是否有办法用更少的代码更有效地循环?我知道有一些叫做列表推导的东西,但我对如何使用它们很困惑。
My questions are how do I remove the error and Is there a way to loop through more efficiently with less code? I know there is something called list comprehensions but I am confused on how to use them.
我知道可以用
pd.options.mode.chained_assignment = None
推荐答案
使用非捕获括号 (?:...)
:
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)$' ]
警告来自此代码:
if regex.groups > 0:
warnings.warn("This pattern has match groups. To actually get the"
" groups, use str.extract.", UserWarning)
因此,只要没有群组,就没有警告。
So as long as there are no groups, there is no warning.
这篇关于Python pandas有效地删除UserWarning和循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文