@ Quang Hoang - более правильный ответ, так как он реализован только с помощью pandas
методов. В любом случае, я оставляю одно решение, используя простой Python:
import pandas as pd
import numpy as np
cols = ['product', 'power', 'brand']
data = [
['product_1', '3 x 1500W', 'brand_A'],
['product_2', '2x1000W + 1x100W', np.nan],
['product 3', '1x1500W + 1x500W', 'brand_B'],
['product 4', '500W', np.nan]
]
df = pd.DataFrame(columns=cols, data=data)
print(df)
Исходные данные:
product power brand
0 product_1 3 x 1500W brand_A
1 product_2 2x1000W + 1x100W NaN
2 product 3 1x1500W + 1x500W brand_B
3 product 4 500W NaN
Спор данных
items = df.power.values.tolist()
brands = df.brand.values.tolist()
res = zip(items, brands)
new_data = []
for idx, aux in enumerate(res):
item, brand = aux
for idx2, power_model in enumerate(item.split('+')):
res = power_model.strip().split('x')
if len(res) == 2:
units, val = res
else:
units = 1
val = res[0]
for _ in range(int(units)):
new_data.append(
[
f'product_{idx + 1}',
val,
brand,
f'product_{idx + 1}_{idx2 + 1}'
]
)
new_cols = ['product', 'power', 'brand', 'new_product']
df2 = pd.DataFrame(columns=new_cols, data=new_data)
print(df2)
Результат
product power brand new_product
0 product_1 1500W brand_A product_1_1
1 product_1 1500W brand_A product_1_1
2 product_1 1500W brand_A product_1_1
3 product_2 1000W NaN product_2_1
4 product_2 1000W NaN product_2_1
5 product_2 100W NaN product_2_2
6 product_3 1500W brand_B product_3_1
7 product_3 500W brand_B product_3_2
8 product_4 500W NaN product_4_1