【问题标题】:Filling column with values (pandas)用值填充列(熊猫)
【发布时间】:2021-03-18 23:05:49
【问题描述】:

我在使用 pandas 填充列中的值时遇到问题。我想添加应该描述客户年收入等级的字符串。我希望数据框长度的 20% 获得“最低”值,9% 的数据框应该获得“中下”等...我想创建一个列表并附加值,然后将其设置为该列的值,但随后我得到一个 ValueError 值长度 (5) 与索引长度 (500) 不匹配

list_of_lists = []
list_of_lists.append(int(0.2*len(df))*"Lowest")
list_of_lists.append(int(0.09*len(df))*"Lower Middle")
list_of_lists.append(int(0.5*len(df))*"Middle")
list_of_lists.append(int(0.12*len(df))*"Upper Middle")
list_of_lists.append(int(0.12*len(df))*"Highest")
df["Annual Income"] = list_of_lists

您知道什么是最好的方法吗?

提前致谢 最好的祝福 阿丽娜

【问题讨论】:

  • 1. list_of_lists 是 5 个字符串的列表,但这些字符串是提供的字符串的重复('LowestLowestLowestLowest...')。而不是乘以字符串,而是乘以列表中的字符串:list_of_lists.append(int(0.2*len(df))*["Lowest"])。使用 list(flatten(list_of_lists)) 来展平列表 (from itertools import flatten)。 2. 这不是一个完整的解决方案:它会失败,因为新列表的大小与数据帧的大小不同,因为所有int(X*len(df)) 的总和不是相同的数据帧长度。
  • 请阅读this。至少,我们需要复制/粘贴的样本数据,以及您希望输出的样子的样本。

标签: python pandas dataframe dataset data-science


【解决方案1】:

您可以使用numpy 进行加权选择。该方法有一个选择列表、要做出的选择的数量和概率。你可以生成这个然后做df['Annual Income'] = incomes

我已打印出数值计数,以便您查看总数。每次都会略有不同。

我还必须调整概率,使它们加起来为 100%

import pandas as pd
from numpy.random import choice
incomes = choice(['Lowest','Lower Middle','Middle','Upper Middle','Highest'], 500,
              p=[.2,.09,.49,.11,.11])

df= pd.DataFrame({'Annual Income':incomes})


df.value_counts()

Annual Income
Middle           245
Lowest            87
Upper Middle      66
Highest           57
Lower Middle      45

【讨论】:

    猜你喜欢
    • 2021-10-04
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多