gpt4 book ai didi

python - Pandas 每行获得前 n 列

转载 作者:行者123 更新时间:2023-12-05 04:24:52 27 4
gpt4 key购买 nike

我有以下数据框:

df1 = pd.DataFrame(data={'1': ['a', 'd', 'g', 'j'], 
'2': ['b', 'e', 'h', 'k'],
'3': ['c', 'f', 'i', 'l'],
'top_n': [1, 3, 2, 1]},
index=pd.Series(['ind1', 'ind2', 'ind3', 'ind4'], name='index'))
>>> df1
1 2 3 top_n
index
ind1 a b c 1
ind2 d e f 3
ind3 g h i 2
ind4 j k l 1

如何根据 top_n 列只获取每一行的前 N ​​个值?

>>> df1
1 2 3 top_n
index
ind1 a NaN NaN 1
ind2 d e f 3
ind3 g h NaN 2
ind4 j NaN NaN 1

在此示例中,ind3 具有 gh,因为 top_n 值为 2。

最佳答案

使用 对于 bool 掩码:

import numpy as np

a = np.ones_like(df1).cumsum(1)

mask = ((a <= df1['top_n'].values[:,None]) | (a == df1.shape[1]))

out = df1.where(mask)

输出:

       1    2    3  top_n
index
ind1 a NaN NaN 1
ind2 d e f 3
ind3 g h NaN 2
ind4 j NaN NaN 1

掩码:

array([[ True, False, False,  True],
[ True, True, True, True],
[ True, True, False, True],
[ True, False, False, True]])

关于python - Pandas 每行获得前 n 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73406790/

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