你可以試試這個:
import pandas as pd
# create frame with six columns of ints
df = pd.DataFrame({'a':[1,2,3,4,10],
'b':[8,5,3,2,11],
'c':[3,7,1,8,8],
'd':[3,7,1,8,8],
'e':[3,1,1,8,8],
'f':[7,7,1,8,8]})
# list of ints
base =[1,2,3,4,5,6]
# define function to count membership of list
def base_count(y):
return sum(True for x in y if x in base)
# apply the function row wise using the axis =1 parameter
df.apply(base_count, axis=1)
輸出:
0 4
1 3
2 6
3 2
4 0
dtype: int64
然後將其分配到一個新的列:
df['g'] = df.apply(base_count, axis=1)
來源
2015-11-05 05:43:51
JAB
向我們展示你的數據框和您想要的結果:HTTP: //stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples –
旋轉你的數據框。在'apply()'中使用'isin()'。 – Kartik