是否可以在pandas中使用自定义过滤器功能?

2024-09-19 23:34:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以用我的助手函数来确定一个镜头是否是三个指针作为Pandas的过滤函数?我的实际函数要复杂得多,但是为了这个问题我简化了它。在

def isThree(x, y):
    return (x + y == 3)

print data[isThree(data['x'], data['y'])].head()

Tags: 函数pandasdatareturndef助手head镜头
3条回答

是的,只要您的函数返回一个具有相同索引的布尔序列,您就可以用输出对原始数据帧进行切片。在这个简单的示例中,我们可以将Series传递给函数:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0, 4, (30, 2)))
def isThree(x, y):
    return x + y == 3

df[isThree(df[0], df[1])]
#    0  1
#2   2  1
#5   2  1
#9   0  3
#11  2  1
#12  0  3
#13  2  1
#27  3  0

是的:

import numpy as np
import pandas as pd

data = pd.DataFrame({'x': np.random.randint(1,3,10),
                     'y': np.random.randint(1,3,10)})
print(data)

输出:

^{pr2}$
def isThree(x, y):
    return (x + y == 3)

print(data[isThree(data['x'], data['y'])].head())

输出:

   x  y
0  1  2
1  2  1
2  2  1
3  1  2
4  2  1

在这种情况下,我建议使用np.where()。请参见以下示例:

import pandas as pd
import numpy as np

df = pd.DataFrame({'x': [1,2,4,2,3,1,2,3,4,0], 'y': [0,1,2,0,0,2,4,0,1,2]})

df['3 Pointer'] = np.where(df['x']+df['y']==3, 1, 0)

产量:

^{pr2}$

相关问题 更多 >