Pandas: 重采样dataframe列,得到对应最大值的离散特征

Pandas: Resample dataframe column, get discrete feature that corresponds to max value

示例数据:

import pandas as pd
import numpy as np
import datetime

data = {'value': [1,2,4,3], 'names': ['joe', 'bob', 'joe', 'bob']}
start, end = datetime.datetime(2015, 1, 1), datetime.datetime(2015, 1, 4)
test = pd.DataFrame(data=data, index=pd.DatetimeIndex(start=start, end=end, 
       freq="D"), columns=["value", "names"])

给出:

          value names
2015-01-01  1   joe
2015-01-02  2   bob
2015-01-03  4   joe
2015-01-04  3   bob

我想按“2D”重新采样并获得最大值,例如:

df.resample('2D')

预期结果应该是:

          value names
 2015-01-01 2   bob
 2015-01-03 4   joe

谁能帮帮我?

您可以重新采样以获得 arg 最大值,然后用它来提取名称和值

(df.resample('2D')[['value']].idxmax()
   .assign(names=lambda x: df.loc[x.value]['names'].values,
           value=lambda x: df.loc[x.value]['value'].values)
)
Out[116]: 
            value names
2015-01-01      2   bob
2015-01-03      4   joe

使用apply和return具有最大值的行。它将通过 resample

标记
test.resample('2D').apply(lambda df: df.loc[df.value.idxmax()])

            value names
2015-01-01      2   bob
2015-01-03      4   joe

除非日期中有缺失值,否则 idxmax 效果很好。例如,如果您每天都重新采样,并且有一天没有值,则 idxmax 不会返回 Nan,而是会引发错误。

以下是解决问题的方法

def map_resample_columns(original_df, resample_df, key_col, cols):
    """
    The function will add the col back to resampled_df
    input: resample_df is resampled from original df based on key_col
    cols: list of columns from original_df to be added back to resample_df    
    """
    for col in cols:
        record_info = []
        for idx, row in resample_df.iterrows():
            val = row[key_col]
            if not np.isnan(val):
                record_info.append(original_df[original_df[key_col] == val][col].tolist()[0])
            else:
                record_info.append(np.nan)
        resample_df[col] = record_info
    return resample_df