【问题标题】:Attach column from one DataFrame to another if col value from 1 within range of values given in the other如果 col 值从 1 在另一个给定的值范围内,则将列从一个 DataFrame 附加到另一个
【发布时间】: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

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    拆分并确保它们的int

    df2[['start', 'end']] = df2['zip'].str.split('-', expand=True).astype(int)

    使用 Series.between

    df1['value'] = df1['zip'].between(df2['start'], df2['end'])
    
       year city  zip  value
    0  2000   NY  100   True
    1  2001   AL  200   True
    2  2002   TX  300   True
    
    

    【讨论】:

    • 感谢您的回答。即使在对两个索引“ValueError:只能比较标记相同的系列对象”进行排序之后,这也会给我这个错误,你如何让 df1 值等于 df2 的“值”列?
    • 确保所有 dtypes 都是 int。要将值从 df2 获取到 df1 您可以合并 [year, city]
    猜你喜欢
    • 1970-01-01
    • 2018-01-26
    • 2021-01-16
    • 2019-06-19
    • 2022-11-23
    • 1970-01-01
    • 2015-07-22
    • 2017-08-06
    • 2020-02-18
    相关资源
    最近更新 更多