Python 输出列中字数大于3的所有行

Python 输出列中字数大于3的所有行,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个虚拟df: columns = ['answer', 'some_number'] data = [['hello how are you doing','1.0'], ['hello', '1.0'], ['bye bye bye bye', '0.0'], ['no', '0.0'], ['yes', '1.0'], ['Who let the dogs out', '0.0'], ['1 +

我有一个虚拟df:

columns = ['answer', 'some_number']
data = [['hello how are you doing','1.0'],
       ['hello', '1.0'],
       ['bye bye bye bye', '0.0'],
        ['no', '0.0'],
        ['yes', '1.0'],
        ['Who let the dogs out', '0.0'],
        ['1 + 1 + 1 + 2', '1.0']]
df = pd.DataFrame(columns=columns, data=data)
我想输出字数大于3的行。 这里的行是“你好”、“再见”、“谁放狗出去了”、“1+1+1+2”

我的方法不起作用:
df[len(df.answer)>3]


输出:
KeyError:True
如果分隔符为
'
,您可以尝试
series.str.count
,否则您可以替换
sep

n=3
df[df['answer'].str.count(' ').gt(n-1)]
包括多个空格
#credits@piRSquared

df['answer'].str.count('\s+').gt(2)
或使用列表理解:

n= 3
df[[len(i.split())>n for i in df['answer']]] #should be faster than above


如果我理解正确,这里有一个方法:

>>> df.loc[df['answer'].str.split().apply(len) > 3, 'answer']
0    hello how are you doing
2            bye bye bye bye
5       Who let the dogs out
6              1 + 1 + 1 + 2
您可以选择列和
len
功能:

>>n=3
>>>df[df.answer.str.split().apply(len)>n]
回答一些问题
0你好1.0怎么样
2再见0.0
5谁放狗出去了0.0
6            1 + 1 + 1 + 2          1.0

为什么
df[len(df.answer)>3]
不起作用?
len(df.answer)
返回
answer
列本身的长度(7),而不是每个
答案的字数(5,1,4,1,1,5,7)

这意味着最后一个表达式的计算结果为
df[7>3]
df[True]
,由于没有列
True
,因此会中断:

>>len(df.answer)
7.
>>>len(df.answer)>3#7>3
真的
>>>df[len(df.answer)>3]#df[True]不存在
KeyError:正确

尝试使用计数进行字符串操作

n = 3
df[[x.count(' ') > n-1 for x in df.answer]]
Out[31]: 
                    answer some_number
0  hello how are you doing         1.0
2          bye bye bye bye         0.0
5     Who let the dogs out         0.0
6            1 + 1 + 1 + 2         1.0

@anky我刚给oneliners计时。
apply
版本稍微快一点。我想这是品味的问题。我总是觉得在不再是字符串的东西上使用
.str
访问器有点奇怪。我投的票是
count
,因为它不会浪费资源创建列表。但是,要包含可能的多个空格:
df['answer'].str.count('\s+').gt(2)
pd.Series.str.count
相比,这一点的有趣之处在于熊猫将自动使用
re
解析
'\s+'
以处理多个空格。此解决方案需要以某种方式使用regex。嗯,我的大脑在这个问题上花了太多时间。
n = 3
df[[x.count(' ') > n-1 for x in df.answer]]
Out[31]: 
                    answer some_number
0  hello how are you doing         1.0
2          bye bye bye bye         0.0
5     Who let the dogs out         0.0
6            1 + 1 + 1 + 2         1.0