2024-09-19 23:34:20 发布
网友
我可以用我的助手函数来确定一个镜头是否是三个指针作为Pandas的过滤函数?我的实际函数要复杂得多,但是为了这个问题我简化了它。在
def isThree(x, y): return (x + y == 3) print data[isThree(data['x'], data['y'])].head()
是的,只要您的函数返回一个具有相同索引的布尔序列,您就可以用输出对原始数据帧进行切片。在这个简单的示例中,我们可以将Series传递给函数:
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)
输出:
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()。请参见以下示例:
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)
产量:
是的,只要您的函数返回一个具有相同索引的布尔序列,您就可以用输出对原始数据帧进行切片。在这个简单的示例中,我们可以将
Series
传递给函数:是的:
输出:
^{pr2}$输出:
在这种情况下,我建议使用
np.where()
。请参见以下示例:产量:
^{pr2}$相关问题 更多 >
编程相关推荐