【问题标题】:Put WHERE clause on Pandas Merge在 Pandas Merge 上放置 WHERE 子句
【发布时间】:2017-11-17 10:29:18
【问题描述】:

我有两个 pandas 数据框,我试图将它们合并到三个不同的键上……有点。每个数据框都有一个性别列和一个我想在其上进行外部连接的 country_destination 列。一个数据框有一个 age_bucket 列,它是一个代表年龄范围的字符串,例如45-49, 50-54, 55-59 我已经用 pandas apply 方法在另一列中变成了一个列表。我的问题是,当您在多个键上的两个数据框之间进行连接时,您是否还可以在某处执行 where 语句以便能够连接不共享相同确切数据类型的列?例如,我可以说“加入这些关于性别的表格,以及用户年龄在 age_gender 的 age_list 列的列表值中的 country_destination 列”

age_gender = pd.read_csv('data/age_gender_bkts.csv')
users = pd.read_csv('data/train_users_2.csv')

def getAgeList(row):
    clean_age = row['age_bucket'].replace('+', '')
    min_max = clean_age.split('-')

    if len(min_max) > 1:
        min_max = list(range(int(min_max[0]), int(min_max[1]) + 1))
    return min_max

age_gender['age_list'] = age_gender.apply(lambda x: getAgeList(x), axis=1)

combined_df = pd.merge(users, age_gender, on=['country_destination', 'gender'])

user.columns

Index(['id', 'date_account_created', 'timestamp_first_active',
       'date_first_booking', 'gender', 'age', 'signup_method', 'signup_flow',
       'language', 'affiliate_channel', 'affiliate_provider',
       'first_affiliate_tracked', 'signup_app', 'first_device_type',
       'first_browser', 'country_destination', 'lat_destination',
       'lng_destination', 'distance_km', 'destination_km2',
       'destination_language ', 'language_levenshtein_distance'],
      dtype='object')

age_gender.columns

Index(['age_bucket', 'country_destination', 'gender',
       'population_in_thousands', 'year', 'age_list'],
      dtype='object')

DataFrame 示例

【问题讨论】:

  • 合并前为什么不过滤数据框?
  • 您能否添加一些数据样本,每个数据帧 2-4 行,并提供所需的输出?我认为minimal, complete, and verifiable example。谢谢。
  • 还有很多列,每个数据框中的2-3列似乎只在样本中是必需的。
  • 是的,我将上传每个数据框头部的照片,只包含其中一些最重要的列。
  • Don't post images of code (or links to them),可以将样本复制为文本吗?

标签: python pandas merge where


【解决方案1】:

我认为您需要按 age_list 列中的值扩展行,然后是 merge

#get lengths of each list
l = age_gender['age_list'].str.len()
#get all columns without age_list
cols = age_gender.columns.difference(['age_list'])
#repeat values by lengths to new DataFrame
df = pd.DataFrame({col: np.repeat(age_gender[col].values, l) for col in cols})
#flattening lists, necessary convert to int, because merge not match
df['age'] = np.concatenate(age_gender['age_list'].values).astype(int)

#inner merge is default, so how='inner' is omit
df1 = pd.merge(df, users, on=['age', 'country_destination'])

【讨论】:

  • 冠军!我觉得在 pandas.merge 中应该有一个内置的方法来做到这一点,但这仍然让我得到了我需要的东西:)。谢谢,我将不得不寻找以文本形式复制 Pandas 数据框的方法,这样我就不必发布它们的图片了。
  • 谢谢。我尝试描述一下解决方案,请稍等。
  • 啊python的力量。感谢您的描述 jezrael !真的很感激。
  • 超级,很高兴能帮上忙。美好的一天!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-28
  • 1970-01-01
相关资源
最近更新 更多