【问题标题】:Python pandas find the column names in descending order for each rowPython pandas 按降序查找每行的列名
【发布时间】:2017-12-24 02:05:10
【问题描述】:

我有以下 pandas 数据框,我正在尝试按降序查找每一行的列名。

A B C D A 1 3 2 1 B 2 1 5 0 C 1 0 1 9 D 2 0 1 2

对于每一行,我尝试按排序顺序(降序)获取列索引 我应该得到: B C D A C A B D 等等 这可以使用熊猫吗?

我正在尝试这样的事情。 test[2].sort_index(axis = 0, ascending = True)

更新 12/23
>>> df1
user_handle  1   2   3   4   5   6   8   9   10  12
user_handle
1             6   0   0   1   0   0   0   0   0   0
2             0  95   0   0   1   0   0   0   1   0
3             0   0   2   0   0   0   0   0   0   0
4             1   0   0  12   0   1   0   0   2   0
5             0   1   0   0   9   0   0   0   0   0
6             0   0   0   1   0  14   0   0   1   0
8             0   0   0   0   0   0   4   0   0   0
9             0   0   0   0   0   0   0  12   0   0
10            0   1   0   2   0   1   0   0  49   0
12            0   0   0   0   0   0   0   0   0   2

>>> t1 = np.flip(df1.values.argsort(), 1)


>>> pd.DataFrame(df1.columns[t1])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "python3.6/site-packages/pandas/core/frame.py", line 303, in __init__
    dtype=dtype)
  File "python3.6/site-packages/pandas/core/frame.py", line 411, in _init_dict
    return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
  File "python3.6/site-packages/pandas/core/frame.py", line 5506, in _arrays_to_mgr
    return create_block_manager_from_arrays(arrays, arr_names, axes)
  File "python3.6/site-packages/pandas/core/internals.py", line 4310, in create_block_manager_from_arrays
    mgr = BlockManager(blocks, axes)
  File "python3.6/site-packages/pandas/core/internals.py", line 2792, in __init__
    (block.ndim, self.ndim))
AssertionError: Number of Block dimensions (3) must equal number of axes (2)
>>>
KeyboardInterrupt

【问题讨论】:

  • 发布您目前尝试过的代码。
  • 我已经粘贴了代码

标签: python pandas dataframe


【解决方案1】:

你可以使用:

temp = np.flip(df.values.argsort(),1)
ndf = pd.DataFrame(df.columns[temp])

   0  1  2  3
0  B  C  D  A
1  C  A  B  D
2  D  C  A  B
3  D  A  C  B

【讨论】:

  • 我也是! flipud 看起来很有用。
  • 请检查您的输出
  • @Vaishali 我更新了,我不知道为什么我用flipud代替flip,对功能的这种误解
  • @andrew_reece 我误解了函数,我们必须在这里使用flip,flipud 反转列和行。
  • 这个好像是最快的
【解决方案2】:

通过使用rankunstack

df.stack().groupby(level=0).rank(method ='first',ascending =False).reset_index(level=1).set_index(0,append=True).unstack()
Out[309]: 
  level_1            
0     1.0 2.0 3.0 4.0
A       B   C   A   D
B       C   A   B   D
C       D   A   C   B
D       A   D   C   B

并使用numpy

pd.DataFrame(df.columns.values[np.lexsort(([df.columns.values]*len(df),df.values))]).iloc[:, ::-1]
Out[351]: 
   3  2  1  0
0  B  C  D  A
1  C  A  B  D
2  D  C  A  B
3  D  A  C  B

【讨论】:

    【解决方案3】:

    您可以使用argsort(),然后索引到columns

    (df.apply(lambda x: (-x).argsort(), axis=1) # use -x for sort descending
       .apply(lambda x: df.columns[x], axis=1))
    
       A  B  C  D
    A  B  C  A  D
    B  C  A  B  D
    C  D  A  C  B
    D  A  D  C  B
    

    注意:如果您不希望最终输出中包含索引和列,只需添加 .values

    【讨论】:

      【解决方案4】:

      使用 numpy argsort,

      pd.DataFrame(df.columns[np.argsort(-df.values, axis=1)])
      
      
          0   1   2   3
      0   B   C   A   D
      1   C   A   B   D
      2   D   A   C   B
      3   A   D   C   B
      

      【讨论】:

      • 我不明白[:, :df.shape[1]]的目的,如果你不使用它会返回相同的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 2020-12-04
      • 2017-02-21
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多