提问人:Pranab 提问时间:7/22/2023 更新时间:7/22/2023 访问量:57
追加与 DataFrame 的最小行值对应的列名以创建新的 DataFrame
Append the column names corresponding to the minimum row values of a dataframe to create a new dataframe
问:
我有以下数据帧
import pandas as pd
data = [[5,4,3,2,6,8], [9,1,5,4,8,6], [7,6,8,1,2,4], [9,6,5,4,8,3]]
df = pd.DataFrame(data, columns=['Col1','Col2','Col3','Col4','Col5','Col6'])
df
我正在尝试显示每行的最小值以及列名。
df=df.min(axis=1)
df
输出:
2
1
1
3
但是,如何附加与这些最小行值相对应的列名呢?
我的预期输出是
2 col4
1 col2
1 col4
3 col6
答:
2赞
Andrej Kesely
7/22/2023
#1
您可以尝试:
df[['Col', 'Value']] = df.apply(lambda x: [idx:=x.idxmin(), x[idx]], axis=1, result_type='expand')
print(df)
指纹:
Col1 Col2 Col3 Col4 Col5 Col6 Col Value
0 5 4 3 2 6 8 Col4 2
1 9 1 5 4 8 6 Col2 1
2 7 6 8 1 2 4 Col4 1
3 9 6 5 4 8 3 Col6 3
如果您只想要 , :Col
Value
print(df[['Col', 'Value']].set_index('Value'))
指纹:
Col
Value
2 Col4
1 Col2
1 Col4
3 Col6
评论