有效地在pandas数据帧中搜索字符串的第一个字符 [英] Efficiently search for first character of a string in a pandas dataframe
问题描述
我有一个pandas数据框列,我需要修改以2开头的那个列的任何条目。现在,我正在使用它,但是非常非常慢:
for i,row in df.iterrows():
if df ['IDnumber'] [i] .startswith('2') ==真:
'''做一些东西'''
我觉得(读) :知道)有一个更有效的方法来做这个而不使用for循环,但我似乎无法找到它。
我试过的其他事情:如果df [df ['IDnumber']。str [0]] =='2':
'''做一些东西'''
如果df [df ['IDnumber']。str.startswith('2')] == True:
'''做一些东西'''
分别给出错误:
KeyError:['2''2''2'...,'1''1''1']不在索引
ValueError:真值DataFrame含糊不清。使用a.empty,a.bool(),a.item(),a.any()或a.all()。
你的意思是你要过滤值所在的行从字符串列开始有一些字符?
>>> df
foobar
0 0foo
1 1foo
2 2foo
3 3foo
4 4foo
5 5foo
6 0bar
7 1bar
8 2bar
9 3bar
10 4bar
11 5bar
>>> df.loc [(df.foobar.str.startswith('2'))]
foobar
2 2foo
8 2bar
然后是:
>>> begining_with_2 = df.loc [(df.foobar.str.startswith('2'))]
>>> for i,row in begining_with_2.iterrows():
... print(row.foobar)
2foo
2bar
I have a pandas data frame column and I need to modify any entry of that column that starts with a 2. Right now, I'm using this which works, but is very, very slow:
for i, row in df.iterrows():
if df['IDnumber'][i].startswith('2') == True:
'''Do some stuff'''
I feel (read: know) there's a more efficent way to do this without using a for loop but I can't seem to find it.
Other things I've tried:
if df[df['IDnumber'].str[0]] == '2':
'''Do some stuff'''
if df[df['IDnumber'].str.startswith('2')] == True:
'''Do some stuff'''
Which respectively give the errors:
KeyError: "['2' '2' '2' ..., '1' '1' '1'] not in index"
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Do you mean you want to filter rows where the value from a string column starts with some character?
>>> df
foobar
0 0foo
1 1foo
2 2foo
3 3foo
4 4foo
5 5foo
6 0bar
7 1bar
8 2bar
9 3bar
10 4bar
11 5bar
>>> df.loc[(df.foobar.str.startswith('2'))]
foobar
2 2foo
8 2bar
Then it is:
>>> begining_with_2 = df.loc[(df.foobar.str.startswith('2'))]
>>> for i, row in begining_with_2.iterrows():
... print(row.foobar)
2foo
2bar
这篇关于有效地在pandas数据帧中搜索字符串的第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!