gpt4 book ai didi

python - 如何使用 idxmax 输出对 pandas 数据框列进行子集化?

转载 作者:太空宇宙 更新时间:2023-11-03 15:30:04 24 4
gpt4 key购买 nike

我有一个 Pandas 数据框:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,40,size=(10,4)), columns=range(4), index = range(10))
df.head()

0 1 2 3
0 27 10 13 21
1 25 12 23 8
2 2 24 24 34
3 10 11 11 10
4 0 15 0 27

我正在使用 idxmax 函数来获取包含最大值的列。

df_max = df.idxmax(1)
df_max.head()

0 0
1 0
2 3
3 1
4 3

我如何使用 df_maxdf,创建一个时间序列值对应于 df 每一行中的最大值?这是我想要的输出:

0    27
1 25
2 34
3 11
4 27
5 37
6 35
7 32
8 20
9 38

我知道我可以使用 df.max(1) 实现这一点,但我想知道如何使用 df_max 获得相同的输出,因为我想要能够将 df_max 应用于与 df 共享相同列和索引(但值不同)的其他矩阵(不是 df) .

最佳答案

你可以试试df.lookup

df.lookup(df_max.index, df_max)

Out[628]: array([27, 25, 34, 11, 27], dtype=int64)

如果需要 Series/DataFrame,将输出传递给 Series/DataFrame 构造函数

pd.Series(df.lookup(df_max.index, df_max), index=df_max.index)

Out[630]:
0 27
1 25
2 34
3 11
4 27
dtype: int64

关于python - 如何使用 idxmax 输出对 pandas 数据框列进行子集化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58470255/

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