简体   繁体   中英

Python: Pandas Dataframe Column Headers Look Strange After Groupby

I implemented the following groupby statement in my code. The purpose of the code below is to provide the minimum date from the "DTIN" column by unique EVENTID.

df_EVENT5_future_2 = df_EVENT5_future.groupby('EVENTID').agg({'DTIN': [np.min]})

df_EVENT5_future_3 = df_EVENT5_future_2.reset_index()

The output table is follows:

EVENTID    DTIN
           amin  
A          1/3/2019
B          1/19/2019
C          2/10/2019

I would like the table to output like this. I don't want the amin to be in the column header.

EVENTID    DTIN
A          1/3/2019
B          1/19/2019
C          2/10/2019

Any help is greatly appreciated.

This is as per @Wen's suggestion. You don't need to use agg for this. Simply use groupby.min() and set as_index=False :

result = df.groupby('EVENTID', as_index=False)['DTIN'].min()

Please do not upvote or accept this answer, as this is a duplicate.

Example

df = pd.DataFrame({'DTIN': {0: 4, 1: 3, 2: 9, 3: 1, 4: 2, 5: 5, 6: 6, 7: 5},
                   'EVENTID': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'C', 5: 'B', 6: 'B', 7: 'C'}})

result = df.groupby('EVENTID', as_index=False)['DTIN'].min()

#   EVENTID  DTIN
# 0       A     3
# 1       B     1
# 2       C     2

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