我的数据框有问题。
我的 df 是:
product power brand
product_1 3 x 1500W brand_A
product_2 2x1000W + 1x100W
product 3 1x1500W + 1x500W brand_B
product 4 500W
我需要将每一行乘以产品数量(扣除幂)
我的 df 预期:
product power brand new_product
product_1 1500W brand_A product_1_1
product_1 1500W brand_A product_1_2
product_1 1500W brand_A product_1_3
product_2 1000W product_2_1
product_2 1000W product_2_2
product_2 100W product_2_3
product 3 1500W brand_B product_3_1
product 3 500W brand_B product_3_2
product 4 500W product_4_1
感谢您的帮助
最佳答案
我会进行字符串提取和合并,然后进行一些清理任务:
df1 = (df.power.str.extractall('(\d+)\s?x\s?(\d+W)')
.reset_index(level=1,drop=True)
)
new_df = df.merge(df1[1].repeat(df1[0]),
left_index=True,
right_index=True,
how='outer')
# update the power column
new_df['power']= np.where(new_df[1].isna(), new_df['power'], new_df[1])
# drop the extra 1 column
new_df.drop(1, axis=1, inplace=True)
# new_product column
new_df['new_product'] = (new_df['product'] + '_' +
new_df.groupby('product').cumcount().add(1).astype(str) )
输出:
product power brand new_product
0 product_1 1500W brand_A product_1_1
0 product_1 1500W brand_A product_1_2
0 product_1 1500W brand_A product_1_3
1 product_2 1000W None product_2_1
1 product_2 1000W None product_2_2
1 product_2 100W None product_2_3
2 product 3 1500W brand_B product 3_1
2 product 3 500W brand_B product 3_2
3 product 4 500W None product 4_1
关于python - 具有条件的重复行 pandas dataframe python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58187756/