【发布时间】:2021-01-27 03:33:55
【问题描述】:
有两个数据框:
df1 = pd.DataFrame({'year':[2000, 2001, 2002], 'city':['NY', 'AL', 'TX'], 'zip':[100, 200, 300]})
df2 = pd.DataFrame({'year':[2000, 2001, 2002], 'city':['NY', 'AL', 'TX'], 'zip':["95-150", "160-220", "190-310"], 'value':[10, 20, 30]})
主 df 是 df1,我想根据匹配的年份、城市和 zip 将 df2 中的“值”列添加到 df1。问题是 df2 的 zip 是在一个范围内给出的,只有当 df1 的 zip 在给定范围内时,我才想附加“值”。我不知道该怎么做。我尝试了一些方法,例如:
# Match indices so that new cols will attach when equal indices
df1 = df1.set_index(['year', 'city'])
df2 = df2.set_index(['year', 'city'])
# Split range of zip into a list
df2['zip'] = df2['zip'].str.split("-")
# Attach 'value' to df1 if df1's zip if greater than df2's min zip AND less than df2's max zip
df1['value'] = df2.loc[(df2['zip'].str[0].astype(int) <= df1['zip']) & \
(df2['zip'].str[1].astype(int) >= df1['zip']), 'value']
这给了我这个错误:ValueError: Can only compare the same-labeled Series objects
【问题讨论】: