Python 如何使用idxmax输出子集数据帧列?
我有一个数据框:Python 如何使用idxmax输出子集数据帧列?,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据框: 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
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_max
和df
,创建与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
这是一个干净短的。ie
df.lookup(df.index,df.idxmax(1))