【问题标题】:Merge child data frame columns to parent data frame with None values in pandas将子数据框列合并到父数据框,在熊猫中没有值
【发布时间】:2021-12-20 01:08:45
【问题描述】:

我有一个这样的熊猫数据框

已编辑

Promotion ID Month Products
PID-1 June Refer below for sample1
PID-2 July Refer below for sample2

样本1: |产品编号| |--| |产品1| |PROD2|

样本2: |产品编号| |--| |产品1| |产品2| |PROD3|

我想把这个数据框变成下面的

Promotion ID Month Products
PID-1 June PROD1
PROD2
PID-2 July PROD 1
PROD2
PROD3

空格可以是NoneNA 值。有没有办法在熊猫中做到这一点而无需遍历行?

【问题讨论】:

  • 你能指定一个列产品的实际例子吗?
  • 如果是一个数据框,其中有一列称为产品 ID

标签: python pandas dataframe merge


【解决方案1】:

您可以像这样使用explode 来展平您的数据框:

#generating data
df = pd.DataFrame([
    ['pid-1', 'June', '| Product Id|  |PROD1| |PROD2|'],
    ['pid-2', 'July', '| Product Id| |PROD1| |PROD2| |PROD3|']
], columns = ['Promotion ID', 'Month', 'Products'])

# extracting the product list
df['Products'] = df['Products']\
    .apply(lambda s: [x for x in re.split(' *\| *', s) if x != '' and x != 'Product Id'])
exploded_df = exploded_df = df.explode('Products', ignore_index=True)

此时dfexploded_df 看起来像这样:

# df
  Promotion ID Month                Products
0        pid-1  June          [PROD1, PROD2]
1        pid-2  July  [PROD1, PROD2, PROD3]

# exploded_df
  Promotion ID Month Products
0        pid-1  June    PROD1
1        pid-1  June    PROD2
2        pid-2  July    PROD1
3        pid-2  July    PROD2
4        pid-2  July   PROD3

我会停在那里。恕我直言,只保留第一行的 MonthPromotion ID 的值只会让你更喜欢。然而,既然你问了,你可以使用ranklocNone 分配给不是第一个组的所有行:

# rank needs a numeric column
exploded_df['index'] = exploded_df.index
# using rank to create a filter on rows that are not the first of their group
filter = exploded_df\
    .groupby(['Promotion ID'])['index']\
    .rank('dense').apply(lambda x: x > 1)
# getting rid of the index column
exploded_df = exploded_df.drop('index', axis=1)
# and voila
exploded_df.loc[filter, ['Month', 'Promotion ID']] = None

结果:

  Promotion ID Month Products
0         None  None    PROD1
1        pid-1  June    PROD2
2         None  None    PROD1
3        pid-2  July    PROD2
4        pid-2  July   PROD3

【讨论】:

  • 感谢您的回答.. 我认为它与我正在寻找的内容相同,但我认为我将您与我的问题形成的方式混淆了.. 我对其进行了编辑以使其成为更清楚一点。 Products 实际上包含一个嵌套的数据框。
  • 只需要在apply函数中改变拆分数据的方式即可。类似[x for x in re.split(' *\| *', s) if x != '' and x != 'Product Id']
  • 我编辑了答案。如果这仍然不是您想要的,请尝试提供一种生成最小示例的方法
  • 你找到答案了吗?
  • 你的答案接近我想要的答案..也是我得到的唯一一个:)
猜你喜欢
  • 1970-01-01
  • 2018-11-18
  • 1970-01-01
  • 2016-10-31
  • 2013-09-26
  • 1970-01-01
  • 2021-03-06
  • 2021-06-30
  • 2022-11-17
相关资源
最近更新 更多