我有一個帶有 product_type 列的資料框,該列在字串中具有重復的子字串:
df1
product_type
bag,bag
tote bag,bag
handbag,handbag
我正在使用此行洗掉重復的子字串以創建新列“unique_type”
df_1['unique_type'] = [set(sub.split(',')) for sub in df_1["product_type"]]
這就是新資料框的樣子
電流輸出
product_type unique_type
bag,bag {'bag'}
tote bag, bag {'tote bag', 'bag'}
{''}
handbag, handbag {'handbag'}
問題是新列 unique_type 中的字串有大括號和引號。我想生成一個包含沒有大括號和引號的字串的列,如下所示:
期望的輸出
product_type unique_type
bag,bag bag
tote bag, bag tote bag, bag
handbag, handbag handbag
uj5u.com熱心網友回復:
添加join:
df_1['unique_type'] = [', '.join(set(sub.split(','))) for sub in df_1["product_type"]]
或者如果需要相同的值順序使用dict.fromkeys技巧:
df_1['unique_type1'] = [', '.join(dict.fromkeys(sub.split(',')))
for sub in df_1["product_type"]]
print (df_1)
product_type unique_type unique_type1
0 bag,bag bag bag
1 tote bag,bag bag, tote bag tote bag, bag
2
3 handbag,handbag handbag handbag
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505720.html
下一篇:如何更改熊貓資料框中的值?
