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