用值填充列 (pandas)

Filling column with values (pandas)

我在 pandas 列中填写值时遇到问题。我想添加描述客户年收入 class 的字符串。我希望数据框长度的 20% 获得值“最低”,数据框的 9% 应该获得“中下”等......我想创建一个列表并附加值,然后将其设置为列的值,但随后我得到一个 ValueError Length of values (5) does not match length of index (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

您知道执行此操作的最佳方法是什么吗?

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

您可以使用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