Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将一组中最常见的结果分配给整个组的Pythonic方法_Python_Pandas_Pandas Groupby - Fatal编程技术网

将一组中最常见的结果分配给整个组的Pythonic方法

将一组中最常见的结果分配给整个组的Pythonic方法,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,我有两个预测因子,A和B,以及一个结果,output,在我的熊猫数据框中,df。 我想将每个A+B组中最常见的结果分配到一个新列prediction 例如,在下面的df中,当A为1且B为0时,结果更可能为-1。 因此,每当a为1且B为0时,我想将-1分配给prediction 下面的代码可以工作,但看起来很不符合Python。 有没有更好的方法来执行这一系列操作 import pandas as pd df = pd.DataFrame({'A' : 10*[0] + 10*[1], 'B'

我有两个预测因子,
A
B
,以及一个结果,
output
,在我的熊猫数据框中,
df
。 我想将每个
A
+
B
组中最常见的结果分配到一个新列
prediction

例如,在下面的
df
中,当
A
为1且
B
为0时,
结果更可能为-1。
因此,每当
a
为1且
B
为0时,我想将-1分配给
prediction

下面的代码可以工作,但看起来很不符合Python。 有没有更好的方法来执行这一系列操作

import pandas as pd

df = pd.DataFrame({'A' : 10*[0] + 10*[1], 'B' : 10*[0,1], 'outcome' : 15*[-1] + 5*[1]})

df

df.groupby(['A', 'B', 'outcome']).size()

temp = df.groupby(['A', 'B', 'outcome']).size().reset_index()
temp.columns = ['A', 'B', 'outcome', 'count']
temp.sort_values(['A', 'B', 'count'], inplace=True, ascending=False)
temp2 = temp[['A', 'B', 'outcome']].drop_duplicates(subset=['A', 'B'])
temp2.rename({'outcome':'prediction'}, inplace=True, axis=1)

temp2

pd.merge(df, temp2, on=['A', 'B'])

让我们尝试使用
模式
转换

s=df.groupby(['A','B']).outcome.transform(lambda x : x.mode()[0])
0    -1
1    -1
2    -1
3    -1
4    -1
5    -1
6    -1
7    -1
8    -1
9    -1
10   -1
11    1
12   -1
13    1
14   -1
15    1
16   -1
17    1
18   -1
19    1
Name: outcome, dtype: int64
df['Fq']=s

让我们尝试使用
模式
转换

s=df.groupby(['A','B']).outcome.transform(lambda x : x.mode()[0])
0    -1
1    -1
2    -1
3    -1
4    -1
5    -1
6    -1
7    -1
8    -1
9    -1
10   -1
11    1
12   -1
13    1
14   -1
15    1
16   -1
17    1
18   -1
19    1
Name: outcome, dtype: int64
df['Fq']=s