【问题标题】:Pandas: Combining dataframes with same column names but different calculationsPandas:组合具有相同列名但计算不同的数据框
【发布时间】:2019-07-24 08:19:42
【问题描述】:

我有两个数据框用于活跃和非活跃客户。活动和非活动数据帧具有相同的列,但 experience_duration 的计算方式不同。

活动样本数据:

ID| join_date | experience_duration| status

 1| 2013-12-05|               4.321| active

 2| 2013-12-05|               4.321| active

样本数据无效:

ID| join_date | experience_duration| status

 5| 2013-12-05|                  14| inactive

 9| 2013-12-05|                  52| inactive

我想将其合并到具有各种客户属性的主客户数据框。它应该看起来像:

ID| join_date  | gender| experience_duration| status

 1| 2013-12-05 |      F|               4.321| active

 2| 2013-12-05 |      M|               4.321| active

 5| 2013-12-05 |      F|                  14| inactive

 9| 2013-12-05 |      F|                  52| inactive

代码:

df_customer = pd.merge(left=df_customer, right=df_active, on=['id'], 
how='left')
df_customer = pd.merge(left=df_customer, right=df_inactive, on=['id'], 
how='left')

问题是我最终会在体验期间出现重复的列。我想要一个体验持续时间列,其中包含基于客户状态的适当值。

【问题讨论】:

  • 看起来您可能想要连接 df 而不是合并它们。单个用户是否可以同时出现在两个 df 中?
  • 否,用户要么处于非活动状态,要么处于活动状态。但是它们可能已经存在于最终的 df 中,我只想添加此列
  • 哦,我明白了,所以实际上有 3 个 df。我第一次阅读这个问题时并不清楚。 experience_duration 列是否已存在于 df_customer 中?您已经在上面展示了一个合并,但您实际上是在与df_customerdf_inactive 进行第二次合并,对吧?您能否编辑您的问题以使其更清楚?
  • df_customer 中不存在 experience_duration。我分别计算非活动和活动。

标签: python pandas


【解决方案1】:

我想你想要:

final_df = pd.concat([activeDf, inactiveDf])

你也可以这样做:

final_df = activeDf.append(inactiveDf)


在这里阅读更多:https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-02
    • 2021-03-20
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 2021-03-20
    相关资源
    最近更新 更多