【问题标题】:I want to create a new frequency column for each column in a pandas dataframe我想为熊猫数据框中的每一列创建一个新的频率列
【发布时间】:2023-02-06 23:56:21
【问题描述】:

假设我有一个这样的数据框:

colors animals
yellow cat
yellow cat
red cat
red cat
blue cat

我想为每一列创建一个列,显示每个值发生的频率:

colors colors_frequency animals animals_frequency
yellow 40% cat 100%
yellow 40% cat 100%
red 40% cat 100%
red 40% cat 100%
blue 20% cat 100%

我试过

frequency = list()
for column in df.columns:
     series = (df[column].value_counts(normalize=True, dropna=True)*100)
     overview.append(series)

#overview list
o_colors = overview[0] 
o_animals = overview[1]

df['animals_frequency'] = o_animals

如果我尝试

df.info()

它返回

Column Non-Null Count Dtype
animals_frequency 0 non-null float64

【问题讨论】:

    标签: python pandas data-analysis exploratory-data-analysis


    【解决方案1】:

    一种简单的方法是计算每个列值的相对频率,然后将这些频率连接回原始 DataFrame。

    for col in df.columns:
        frequency = df[col].value_counts(normalize=True)
        frequency.name = f"{col}_frequency"
        df = df.merge(frequency.to_frame(), left_on=col, right_index=True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      • 2021-04-06
      • 2019-12-27
      • 1970-01-01
      • 2023-02-05
      • 2015-03-28
      相关资源
      最近更新 更多