gpt4 book ai didi

Python pandas 按降序查找每一行的列名

转载 作者:太空宇宙 更新时间:2023-11-03 12:16:58 33 4
gpt4 key购买 nike

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


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

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

我正在尝试这样的事情。
测试 [2].sort_index(轴 = 0,升序 = 真)

更新 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

最佳答案

你可以使用:

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

关于Python pandas 按降序查找每一行的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47879262/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com