I have a pandas dataframe for example
Col1 | Col2 | Col3 |
---|---|---|
-1 | 2 | -3 |
I want to pick the minimum absolute value: table2
Col1 | Col2 | Col3 | Result |
---|---|---|---|
-1 | 2 | -3 | -1 |
For now I am using df.abs().idxmin(axis="columns")
and I get: table3
Col1 | Col2 | Col3 | Result |
---|---|---|---|
-1 | 2 | -3 | Col1 |
I would like to ask how can I convert table 3 to table 2?
CodePudding user response:
Use np.argmin
(numpy counterpart of DataFrame.idxmin
). Since you want to extract the original values, it's more convenient to access those values at the numpy level.
I added an extra row to your MRE for demonstration:
cols = np.argmin(df.abs().to_numpy(), axis=1) # [0, 2]
rows = range(len(cols)) # [0, 1]
df['Result'] = df.to_numpy()[rows, cols]
# Col1 Col2 Col3 Result
# 0 -1 2 -3 -1
# 1 10 -5 4 4
CodePudding user response:
You can use df.abs().min(axis=1)
>>> import pandas as pd
>>>
>>> data = {'col1': [1], 'col2': [2], 'col3': [-3]}
>>> df = pd.DataFrame(data)
>>> df
col1 col2 col3
0 1 2 -3
>>> df['Result'] = df.abs().min(axis=1)
>>> df
col1 col2 col3 Result
0 1 2 -3 1
CodePudding user response:
Try:
df = pd.read_clipboard()
print(df)
# Col1 Col2 Col3
# 0 -1 2 -3
df['Result'] = df.abs().idxmin(axis=1)
print(df)
# Col1 Col2 Col3 Result
# 0 -1 2 -3 Col1
df['Result'] = df.loc[:, df['Result']]
print(df)
# Col1 Col2 Col3 Result
# 0 -1 2 -3 -1
Output:
Col1 Col2 Col3 Result
0 -1 2 -3 -1