![](/img/trans.png)
[英]how to create new column names from another column all values and agg by another column in pandas dataframe?
[英]How to split and keep all the values from a dataframe in new column?
我需要拆分Product and Quantity
列。 新列名稱為Quantity
。
如果您看到下面的示例,一些行將以 [2] 中的數量信息和其他 [1] 中的信息開頭。 另外,我不能使用 [-] 因為在下面的示例中,'-' 上的第二個拆分將起作用,但第 3 行和第 4 行將不正確
Product and Quantity
ABC-BBC-Bottle- 1 - 30 mg
BBC-44-Capsule- 10 - 500mg
KKP-Bottle- 5 - 30 mg
R2B-Powder-500mg
我需要以下幫助:
目前,它如下所示。
df = source_df[['Product and Quantity']]
df['Quantity'] = df['Product and Quantity'].str.split('-').str[2]
輸出如下所示。
Quantity
Bottle
Capsule
5
500mg
我希望它看起來像下面這樣。
Quantity
Bottle - 1 - 30 mg
Capsule - 10 - 500mg
Bottle - 5 - 30 mg
Powder - 500mg
可靠的方法:使用正則表達式!
regex = r'[^-]+-((?:[^-]+-){,2}[^-]+)$'
df['Quantity'] = df['Product and Quantity'].str.extract(regex)
輸出:
Product and Quantity Quantity
0 ABC-BBC-Bottle- 1 - 30 mg Bottle- 1 - 30 mg
1 BBC-44-Capsule- 10 - 500mg Capsule- 10 - 500mg
2 KKP-Bottle- 5 - 30 mg Bottle- 5 - 30 mg
3 R2B-Powder-500mg Powder-500mg
df['Quantity'] = df[0].str.replace(' ', '').str.findall('\w+-\d*-*\d*mg').str[0].str.replace('-', ' - ')
輸出:
Product and Quantity Quantity
0 ABC-BBC-Bottle- 1 - 30 mg Bottle - 1 - 30mg
1 BBC-44-Capsule- 10 - 500mg Capsule - 10 - 500mg
2 KKP-Bottle- 5 - 30 mg Bottle - 5 - 30mg
3 R2B-Powder-500mg Powder - 500mg
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.