简体   繁体   中英

Pandas Idxmax on a date-value DataFrame

Given this DataFrame:

import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'Date':['20/03/17 10:30:34','20/03/17 10:31:24','20/03/17 10:34:34'],
                   'Value':[4,7,5]})

df['Date'] = pd.to_datetime(df.Date)
df
Out[53]: 
                 Date  Value
0 2017-03-20 10:30:34      4
1 2017-03-20 10:31:24      7
2 2017-03-20 10:34:34      5

Im am trying to extract the max value and its index. I can get the max value by df.Value.max() but when I use df.idxmax() to get the Index fo the value I get a TypeError:

TypeError: float() argument must be a string or a number

Is there any other way to get the Index of the Max value of a Dataframe? (Or any way to correct this one?)

Because it should be:

df.Value.idxmax()

It then returns 1.

You have to specify from which column you want to get maximum value-idx.

To get the idx of maxumum value use:

df.Value.idxmax()

if you want to get the idx of maximum Date use:

df.Date.idxmax()

If you only care about the Value column, you can use:

df.Value.idxmax()
>>> 1

However, it is strange that it fails on both columns with df.idxmax() as the following works, too:

df.Date.idxmax()
>>> 2

df.idxmax() also works for some other dummy data:

dummy = pd.DataFrame(np.random.random(size=(5,2)))
print(dummy)    

    0           1
0   0.944017    0.365198
1   0.541003    0.447632
2   0.583375    0.081192
3   0.492935    0.570310
4   0.832320    0.542983

print(dummy.idxmax())

0    0
1    3
dtype: int64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM