Search code examples
pythonpandasindexingminimum

Python/Pandas: Idx and ix


When I try to index the smallest value in a column using Pandas, it converts my DataFrame into an object instead of a DataFrame with one row. I would like to revert back to a DataFrame even if it's just a single row.

for j in Amount_ref:
    group['helper'] = np.abs(group['Amount'] - j)
    closest = group.ix[group['helper'].idxmin()]
    print(closest)

This is the output I am getting:

LoanAgreementID    E2502C04-DBC3-E611-8126-06CAB7997043
Amount                                           566.12
TransactionDate              2016-12-16 14:00:20.243000
ContactID          001A29DC-9253-E611-8126-06CAB7997043
PaymentType                                         NaN
CashLedgerType                                        5
KeyValue_String                                  Cheque
KeyValue_String                                    None
AutoNumber                                        54980
IssueDate                           2016-12-15 00:00:00
helper                                                0
Name: 2, dtype: object

Solution

  • This should help:

    closest.to_frame().T
    

    or:

    index = group['helper'].idxmin()
    closest = group.loc[index:index]