![](/img/trans.png)
[英]pandas get the min/max value of a row in a dataframe of only those rows that contain a certain string in another column
[英]get dataframe rows that contain values in a column that are close to those in a corresponding column in another dataframe
我有兩個數據框,我正在嘗試搜索每個數據框內的事件,其中每個數據框內一個專門標記的列下的兩個值彼此接近,但是我不知道如何做到這一點。 我已經嘗試過isin,但是對於我在這里嘗試做的事情似乎太有限了。
問題的關鍵點已經接近 。 我不僅對值完全相同的事件感興趣。
即
DF1
a
0 10
1 100
2 1000
3 5000
4 6000
DF2
a
0 1
1 150
2 800
3 1002
4 5997
假設我對df1和df2中的行感興趣,其中a在彼此的+-3范圍內,那么我如何才能得到一個數據框,該數據框只限於那些在a中具有相應值的行,而在另一行中得到
DF1
a
2 1000
4 6000
和
DF2
a
3 1002
4 5997
?
這是一個簡單的方法:
import numpy as np
import pandas as pd
THRESHOLD = 3
df1 = pd.DataFrame({'a': [10, 100, 1000, 5000, 6000]}, index=range(5))
df2 = pd.DataFrame({'a': [1, 150, 800, 1002, 5997]}, index=range(5))
m = np.abs(df1.a[:, np.newaxis] - df2.a[np.newaxis, :]) <= THRESHOLD
df1_close = df1[np.any(m, axis=1)]
df2_close = df2[np.any(m, axis=0)]
print('df1_close', df1_close, '', 'df2_close', df2_close, sep='\n')
輸出:
df1_close
a
2 1000
4 6000
df2_close
a
3 1002
4 5997
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.