【发布时间】: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