python - 具有条件的重复行 pandas dataframe python

标签 python regex pandas dataframe

我的数据框有问题。

我的 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/

相关文章:

python - 如何使用 azure-sdk-for-python 删除磁盘?

regex - 删除字符串末尾的句点和数字

python - df.head() 和 df.head 有什么区别?

Python:如何从内存中的zip文件读取图像?

python - 如何显示 blobstore 中的图像?

php - 在字符串中查找 HTML 标签

c++ - 如何获得 std::regex 的所有可能匹配项

python - 如何通过文件处理从给定的数据框列中获取唯一对?

python - Pandas 假期套餐黑色星期五折扣

python - 如何使用通过 webdriver_manager 安装的 ChromeDriver 更改 Google Chrome UserAgent