【发布时间】:2022-01-14 04:01:11
【问题描述】:
在我的数据集中,我有三列:产品、市场和产品类型。对于具有不同产品类型的产品,我必须将 product_type 值替换为以下顺序的值:marketplace = 200、300、400 和 500。输入文件如下所示:
product Marketplace product_type
1 200 X
2 300 A
2 400 A
2 200 A
3 500 A
3 400 A
3 300 B
这是输出的样子:
product Marketplace product_type
1 200 X
2 300 A
2 400 A
2 200 A
3 500 B
3 400 B
3 300 B
因为我们无法获取市场 == 200 的信息,我们将切换到市场 == 300 并替换我拥有的所有集合的值,产品 == 3。 这是我使用的代码:
mp_correspondence = {200:1,
300:2,
400:3,
500:4,
}
df['ranking'] = df['marketplace'].map(mp_correspondence)
number_list = set(df['product '])
for i in product_list:
df_product_frame = df[df['product '] == i].copy()
nr_rows = df_product_frame['product'].count()
if nr_rows > 1:
product_type_count = set(df_product_frame['product_type'])
print(product_type_count )
preced_value = set(df['ranking'])
print(preced_value)
if product_type_count != 1:
res = next(iter(preced_value))
print("The first key of dictionary is:" + str(res))
else:
print('Lesser than 1')
但最重要的是,优先排名列未显示与市场产品类型相关的正确值。有什么方法可以帮助您解决错误并获得替换值的方法?
【问题讨论】:
标签: python pandas dataframe dictionary replace