【问题标题】:New column for DataFrame based on another DataFrame基于另一个 DataFrame 的 DataFrame 的新列
【发布时间】:2018-07-23 09:02:35
【问题描述】:

我想将“文本”列与 B 值最接近

a = np.array(range(10, 35, 5))
b = np.array(range(0, 30, 5)) + 2
b_text = [random.choice(string.ascii_letters) for i in range(len(b))]
df1 = pd.DataFrame(a, columns=['A'])
df2 = pd.DataFrame(list(zip(b, b_text)), columns=['B', 'text'])

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    我认为需要merge_asof:

    #if problem with different dtypes
    #df1['A'] = df1['A'].astype(np.int64)
    #df2['B'] = df2['B'].astype(np.int64)
    
    df = pd.merge_asof(df1, df2, left_on='A', right_on='B')
    print (df)
        A   B text
    0  10   7    R
    1  15  12    y
    2  20  17    i
    3  25  22    a
    4  30  27    G
    

    【讨论】:

    • 您的解决方案完全符合我的要求,但我的问题是错误的。我需要使用多个具有不同条件的列,并希望找到更通用的方法。你能给我建议我应该在文档中查看哪个方向吗?
    • @typae - 这取决于您的功能,我认为带有参数methodreindex 应该会有所帮助,或者应该由map 创建另一个解决方案,例如this 解决方案。
    猜你喜欢
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 2015-12-06
    • 2016-11-14
    • 2020-11-30
    相关资源
    最近更新 更多