Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.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
Python 在数据帧上计算模式而不排序结果_Python_Pandas_Dataframe_Mode - Fatal编程技术网

Python 在数据帧上计算模式而不排序结果

Python 在数据帧上计算模式而不排序结果,python,pandas,dataframe,mode,Python,Pandas,Dataframe,Mode,我有这样一个数据框: df = pd.DataFrame({'a1': [2,3,4,8,8], 'a2': [2,5,7,5,10], 'a3':[1,9,4,10,2]}) a1 a2 a3 0 2 2 1 1 3 5 9 2 4 7 4 3 8 5 10 4 8 10 2 输出应为: 0 2 1 3 2 4 3 8 4 8 操作:我想按行计算模式,如果模式不存在,我想从a1(第一列)中得到值 例如:在

我有这样一个数据框:

df = pd.DataFrame({'a1': [2,3,4,8,8], 'a2': [2,5,7,5,10], 'a3':[1,9,4,10,2]})

    a1  a2  a3
0   2   2   1
1   3   5   9
2   4   7   4
3   8   5   10
4   8   10  2
输出应为:

0  2 
1  3
2  4
3  8 
4  8
操作:我想按行计算模式,如果模式不存在,我想从a1(第一列)中得到值

例如:在第二行
(3,5,9)
,模式不存在,因此我在输出中得到
3


注意:我已经尝试了
df.mode(axis=1)
,但这似乎会将值序列按行洗牌,因此我并不总是获得输出中第一列的值。
无排序方法

agg
+
集合。计数器
。不对模式进行排序


模式排序方法

  • 沿第一个轴使用
    模式
    ,然后选择先到的:

    df.mode(axis=1).iloc[:, 0]
    
    或者

  • scipy.stats.mode

    from scipy.stats import mode
    np.array(mode(df, axis=1))[0].squeeze()
    array([2, 3, 4, 5, 2])
    

  • 还有一个选项是使用
    np。其中

    mode = df.mode(axis=1)
    np.where(mode.iloc[:,-1].isnull(),
        mode.iloc[:,0], # No tie, use the calculated mode 
        df.iloc[:,0]) # Tie, use the first column of the original df
    # array([2., 3., 4., 8., 8.])
    

    为什么不干脆
    df.mode(axis=1)[0]
    ?请检查问题中的注释。很抱歉,我应该先更新它。@cᴏʟᴅsᴘᴇᴇᴅ 你的回答在某些情况下不成立。我已经用新行更新了df。请检查。@ MunsiSalasWAT HI,如果这是你所需要的,你能考虑接受吗?ᴏʟᴅsᴘᴇᴇᴅ 这最终解决了问题。我会接受你的回答,因为你没有放弃。我已经更新了问题。棘手的部分不见了。我不认为这是重复的。你说的“模式不存在”是指有一条领带吗?@BallpointBen是的,没错。
    0    2.0
    1    3.0
    2    4.0
    3    5.0
    4    2.0
    Name: 0, dtype: float64
    
    from scipy.stats import mode
    np.array(mode(df, axis=1))[0].squeeze()
    array([2, 3, 4, 5, 2])
    
    mode = df.mode(axis=1)
    np.where(mode.iloc[:,-1].isnull(),
        mode.iloc[:,0], # No tie, use the calculated mode 
        df.iloc[:,0]) # Tie, use the first column of the original df
    # array([2., 3., 4., 8., 8.])