Pandas:如何根据字符串的长度过滤行

762 阅读2分钟

你可以使用以下方法来过滤pandas DataFrame中包含特定长度的字符串的行

方法1:基于一列字符串长度的过滤行

#filter rows where col1 has a string length of 5
df.loc[df['col1'].str.len() == 5]

方法2:基于多列字符串长度的过滤行列

#filter rows where col1 has string length of 5 and col2 has string length of 7
df.loc[(df['col1'].str.len() == 5) & (df['col2'].str.len() == 7)]

下面的例子展示了如何通过以下pandas DataFrame实际使用每种方法:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'conf': ['East', 'East', 'North', 'West', 'North', 'South'],
                   'pos': ['Guard', 'Guard', 'Forward', 'Center', 'Center', 'Forward'],
                   'points': [5, 7, 7, 9, 12, 9]})

#view DataFrame
print(df)

    conf      pos  points
0   East    Guard       5
1   East    Guard       7
2  North  Forward       7
3   West   Center       9
4  North   Center      12
5  South  Forward       9

例1:基于一列字符串长度的过滤行

下面的代码显示了如何过滤DataFrame中conf列中字符串长度为5的:

#filter rows where conf has a string length of 5
df.loc[df['conf'].str.len() == 5]

	conf	pos	points
2	North	Forward      7
4	North	Center	    12
5	South	Forward	     9

只有conf列的字符串长度为5的行被返回。

我们可以看到,在conf列中有两个不同的字符串符合这个标准:

  • "北"
  • "南方"

这两个字符串的长度都是5

例2:基于多列字符串长度的过滤行

下面的代码显示了如何过滤DataFrame中conf列的字符串长度为5pos列的字符串长度为7的行

#filter rows where conf has string length of 5 and pos has string length of 7
df.loc[(df['conf'].str.len() == 5) & (df['pos'].str.len() == 7)]

        conf	pos	points
2	North	Forward	     7
5	South	Forward	     9

只有conf列的字符串长度为5pos列的强度长度为7的行被返回。

注意:你可以在这里找到pandas中str.len()函数的完整文档。

其他资源

下面的教程解释了如何在pandas中执行其他常见操作。

如何根据条件在Pandas数据框架中删除行
如何根据多个条件过滤Pandas数据框架
如何在Pandas数据框架中使用 "NOT IN "过滤器