gpt4 book ai didi

Python Pandas : Inconsistent behaviour of boolean indexing on a Series using the len() method

转载 作者:行者123 更新时间:2023-12-01 03:38:59 25 4
gpt4 key购买 nike

我有一系列字符串,我需要使用 len() 对其应用 bool 索引。

在一种情况下它有效,在另一种情况下它不起作用:

工作案例是数据帧上的groupby,后跟结果系列上的unique()apply(str)将生成的 numpy.ndarray 条目更改为字符串:

import pandas as pd
df = pd.DataFrame({'A':['a','a','a','a','b','b','b','b'],'B':[1,2,2,3,4,5,4,4]})
dg = df.groupby('A')['B'].unique().apply(str)
db = dg[len(dg) > 2]

这工作正常并产生所需的结果:

>>db
Out[119]: '[1 2 3]'

但是下面的代码会抛出KeyError: True:

ss = pd.Series(['a','b','cc','dd','eeee','ff','ggg'])
ls = ss[len(ss) > 2]

对象dgss都只是字符串系列:

>>type(dg)
Out[113]: pandas.core.series.Series

>>type(ss)
Out[114]: pandas.core.series.Series

>>type(dg['a'])
Out[115]: str

>>type(ss[0])
Out[116]: str

我遵循文档中描述的语法:http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing

我可以看到潜在的冲突,因为 len(ss) 本身返回系列本身的长度,现在精确的命令用于 bool 索引 ss[len(ss) > 2],但我预计这两个示例都不起作用。

现在这种行为似乎不一致,除非我遗漏了一些明显的东西。

最佳答案

我认为你需要str.len ,因为需要 Series 每个值的长度:

ss = pd.Series(['a','b','cc','dd','eeee','ff','ggg'])

print (ss.str.len())
0 1
1 1
2 2
3 2
4 4
5 2
6 3
dtype: int64

print (ss.str.len() > 2)
0 False
1 False
2 False
3 False
4 True
5 False
6 True
dtype: bool

ls = ss[ss.str.len() > 2]
print (ls)
4 eeee
6 ggg
dtype: object

如果使用len,则获取Series的长度:

print (len(ss))
7

另一个解决方案是 apply 长度:

ss = pd.Series(['a','b','cc','dd','eeee','ff','ggg'])
ls = ss[ss.apply(len) > 2]
print (ls)
4 eeee
6 ggg
dtype: object

第一个脚本错误,需要apply len 还有:

df = pd.DataFrame({'A':['a','a','a','a','b','b','b','b'],'B':[1,2,2,2,4,5,4,6]})
dg = df.groupby('A')['B'].unique()
print (dg)
A
a [1, 2]
b [4, 5, 6]
Name: B, dtype: object

db = dg[dg.apply(len) > 2]
print (db)
A
b [4, 5, 6]
Name: B, dtype: object

如果将 list 转换为 str,您将得到另一个 len(数据的length + [] 的长度+ 空格长度):

dg = df.groupby('A')['B'].unique().apply(str)
print (dg)
A
a [1 2]
b [4 5 6]
Name: B, dtype: object

print (dg.apply(len))
A
a 5
b 7
Name: B, dtype: int64

关于Python Pandas : Inconsistent behaviour of boolean indexing on a Series using the len() method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39972874/

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