[英]How can I convert string like '3x a;2x b' to string 'a a a b b' in Python?
我有一個 pandas dataframe 其中一列是帶有類別的列。 該列中的行格式類似於 '3x category1;4x category2; 等等'。 對於這樣的每一行,我想獲得類別重復x次的字符串。
這是我所擁有的示例
df = pd.DataFrame(data= {'categories': ['3x bank;6x call center', '3x silent call;4x another'],
'phone_number': [79294347795, 79242935107]})
df
| categories | phone_number
----|---------------------------|--------------
0 | 3x bank;2x call center | 79294347795
----|---------------------------|--------------
1 | 2x silent call;2x another | 79242935107
這就是我想要得到的
| categories | phone_number
----|-----------------------------------------|---------------
0 | bank bank bank call center call center | 79294347795
----|-----------------------------------------|---------------
1 | silent call silent call another another | 79242935107
IIUC,你想要這樣的東西:
df = pd.DataFrame({'category':['3x a', '4x b', '5x e']})
df1 = df['category'].str.extract('(?P<num>\d)x (?P<cat>\w+)')
df1['cat'].repeat(df1['num'])
Output:
0 a
0 a
0 a
1 b
1 b
1 b
1 b
2 e
2 e
2 e
2 e
2 e
Name: cat, dtype: object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.