【问题标题】:pandas groupby column values and replace grouped values in another columnpandas groupby 列值并替换另一列中的分组值
【发布时间】:2022-06-13 09:53:32
【问题描述】:

我有一个这样的数据框:

Ticker instrument_name year month instrument_type expiry_type
ABAN10SEPFUT ABAN 10 SEP FUT NaN
ABAN10OCTFUT ABAN 10 OCT FUT NaN
ABAN10NOVFUT ABAN 10 NOV FUT NaN

我想按 instrument_type ('FUT') 分组并在 month 中查找唯一值。 然后将唯一值与 month 列进行比较,并将 expiry_type 列中的值替换为 'I','II','III'。

预期结果:

Ticker instrument_name year month instrument_type expiry_type
ABAN10SEPFUT ABAN 10 SEP FUT I
ABAN10OCTFUT ABAN 10 OCT FUT II
ABAN10NOVFUT ABAN 10 NOV FUT III

我的代码看起来像 #1

def condition(x):
if x =='SEP':
    return "I"
elif x =='OCT':
    return "II"
elif x =='NOV':
    return "III"
else:
    return ''

#2

for index, row in path.iterrows():
    data = pd.read_parquet(row['location'])
    data['expiry_type'] = np.where((data['instrument_type'] == 'FUT'),data['month'].apply(condition),'')

由于我已经知道月份列中的唯一值,所以我创建了一个自定义函数来替换 expiry_type 列中的值。我有类似的文件,所以有没有办法找到唯一值并自动替换。 我怎么做?提前谢谢!

【问题讨论】:

    标签: python pandas numpy pandas-groupby


    【解决方案1】:

    考虑到您已按 instrument_type 分组,您可以构建一个类似于 #1 中的函数:

    def condition(x):
        if x.month =='SEP':
            return "I"
        elif x.month =='OCT':
            return "II"
        elif x.month =='NOV':
            return "III"
        else:
            return ''
    

    并将此函数应用于expiry_type 列:

    df['expiry_type'] = df.apply(condition, axis = 1).
    

    【讨论】:

    • 看来我的问题不清楚,让我再解释一次。如果我将 instrument_type ('FUT') 分组,我将在月份列中拥有三个唯一值,如 SEP、OCT 和 NOV。不知何故,我想保存这些唯一值并再次与月份列进行比较,并替换 expiry_type 列中的值('I','II','III')。事情是月份列中的唯一值将更改我正在迭代的每个文件。因此,我不想在函数中定义唯一值,而是想自动化这个过程
    【解决方案2】:

    您可以使用 Pandas unique 函数查找列中的唯一值。对您拥有的每个 DataFrame 使用 for 循环,在 month 列上应用 unique 函数以获得唯一值列表。然后,使用这些值作为键和新的表示形式(在这个特定示例中为罗马数字)作为值来创建一个字典。然后,您可以使用map 函数替换month 列中的值并将新值分配给expiry_type 列。

    def toRoman(n):
        roman = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII']
        return roman[n]
    
    df_list = ['df1.csv', 'df2.csv', 'df3.csv']
    for df_file in df_list:
        df = pd.read_csv(df_file)
        g = df.groupby('instrument_type')
        uniq = g['month'].unique()[0]
        # create a dictionary using the unique values
        dict_map = {name:toRoman(idx) for idx,name in enumerate(uniq)}
        df['expiry_type'] = df['month'].map(dict_map)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-16
      • 1970-01-01
      • 2019-04-04
      • 1970-01-01
      • 2021-03-31
      • 1970-01-01
      • 1970-01-01
      • 2018-03-01
      相关资源
      最近更新 更多