如何将应用函数链接到 pandas 数据帧的子集
How to chain apply functions to subset a pandas dataframe
我有一个 pandas 数据框,我想根据两个函数 is_long()
和 is_short()
的应用对其进行子集化。第一个必须 return True,第二个必须 return True 才能使该行成为子集。例如:
import pandas as pd
data = [['foo', 10], ['baar', 15], ['baz', 14], ['baaar', 15]]
df = pd.DataFrame(data, columns = ['name', 'age'])
df
def is_long(x):
assert isinstance(x, str)
return True if len(x) > 2 else False
def is_short(x):
assert isinstance(x, str)
return True if len(x) < 4 else False
以下应该 return 行 name
的长度为 3:
df[df['name'].apply(is_long).apply(is_short)]
应该return:
name age
0 foo 10
2 baz 14
但是第二个应用没有在数据帧上执行,因为它return是一个断言错误:
11
12 def is_short(x):
---> 13 assert isinstance(x, str)
14 return True if len(x) < 4 else False
AssertionError:
我的问题是 - 如何优雅地将两个应用函数链接在一起(无需编写两行单独的代码),以便它们作用于同一列并按顺序执行?
如有任何建议,我们将不胜感激。
如果你想用apply()
方法来做,那么
而不是:
df[df['name'].apply(is_long).apply(is_short)]
Do/Use这个:
df[df.loc[df['name'].apply(is_long),'name'].apply(is_short)]
或
df[df['name'].apply(lambda x: is_long(x) & is_short(x))]
上述方法的输出:
#output
name age
0 foo 10
2 baz 14
解释:
在您的代码中:df[df['name'].apply(is_long).apply(is_short)]
df['name'].apply(is_long)
给出了 True
的 boolean series
并且您通过将另一个 apply()
方法链接到它来将该布尔系列传递给 is_short()
函数,这就是为什么你得到 AssertionError
因为你在你的 is_short()
函数中使用了 assert
关键字并且你的条件 isinstance(x, str)
不满足
您可以将这两个函数包装在 lambda
意义上的函数中,即:
df[df.name.apply(lambda x: is_long(x) and is_short(x))]
获得
name age
0 foo 10
2 baz 14
我有一个 pandas 数据框,我想根据两个函数 is_long()
和 is_short()
的应用对其进行子集化。第一个必须 return True,第二个必须 return True 才能使该行成为子集。例如:
import pandas as pd
data = [['foo', 10], ['baar', 15], ['baz', 14], ['baaar', 15]]
df = pd.DataFrame(data, columns = ['name', 'age'])
df
def is_long(x):
assert isinstance(x, str)
return True if len(x) > 2 else False
def is_short(x):
assert isinstance(x, str)
return True if len(x) < 4 else False
以下应该 return 行 name
的长度为 3:
df[df['name'].apply(is_long).apply(is_short)]
应该return:
name age
0 foo 10
2 baz 14
但是第二个应用没有在数据帧上执行,因为它return是一个断言错误:
11
12 def is_short(x):
---> 13 assert isinstance(x, str)
14 return True if len(x) < 4 else False
AssertionError:
我的问题是 - 如何优雅地将两个应用函数链接在一起(无需编写两行单独的代码),以便它们作用于同一列并按顺序执行?
如有任何建议,我们将不胜感激。
如果你想用apply()
方法来做,那么
而不是:
df[df['name'].apply(is_long).apply(is_short)]
Do/Use这个:
df[df.loc[df['name'].apply(is_long),'name'].apply(is_short)]
或
df[df['name'].apply(lambda x: is_long(x) & is_short(x))]
上述方法的输出:
#output
name age
0 foo 10
2 baz 14
解释:
在您的代码中:df[df['name'].apply(is_long).apply(is_short)]
df['name'].apply(is_long)
给出了 True
的 boolean series
并且您通过将另一个 apply()
方法链接到它来将该布尔系列传递给 is_short()
函数,这就是为什么你得到 AssertionError
因为你在你的 is_short()
函数中使用了 assert
关键字并且你的条件 isinstance(x, str)
不满足
您可以将这两个函数包装在 lambda
意义上的函数中,即:
df[df.name.apply(lambda x: is_long(x) and is_short(x))]
获得
name age
0 foo 10
2 baz 14