簡體   English   中英

基於另一個DataFrame的DataFrame的新列

[英]New column for DataFrame based on another DataFrame

我想將“文本”列與B值最接近<= A值的第一個DataFrame合並。 DataFrames長度不相等。

例

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'])

我認為需要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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM