在两列 python 数据框之间的范围内搜索特定值

Searching a particular value in a range among two columns python dataframe

我有两个 csv files.Depending 基于 csv 文件 1 中单元格的值我应该能够在 csv 文件 2 的列中搜索该值并从 csv 文件中的其他列获取相应的值2. 很抱歉,如果这个 confusing.It 可能会通过插图

变得清楚

CSV 文件 1

Car   Mileage
 A       8
 B       6
 C       10

CSV 文件 2

Score  Mileage(Min)    Mileage(Max)
 1       1                 3
 2       4                 6
 3       7                 9
 4       10                12 
 5       13                15 

我想要的输出 CSV 文件是这样的

Car    Mileage     Score
 A       8           3
 B       6           2
 C       10          4

汽车 A 根据其里程 8 获得 3 分,然后在 csv 文件 2 中查看该里程在哪个范围内,然后获得该范围的相应分值。 任何帮助将不胜感激 提前致谢

As of writing this, the current stable release is v0.21.

要阅读您的文件,请使用 pd.read_csv -

df0 = pd.read_csv('file1.csv')
df1 = pd.read_csv('file2.csv')

df0

  Car  Mileage
0   A        8
1   B        6
2   C       10

df1

   Score  Mileage(Min)  Mileage(Max)
0      1             1             3
1      2             4             6
2      3             7             9
3      4            10            12
4      5            13            15

要查找分数,请通过调用 IntervalIndex.from_tuples 使用 pd.IntervalIndex。这应该很快 -

v = df1.loc[:, 'Mileage(Min)':'Mileage(Max)'].apply(tuple, 1).tolist()
idx = pd.IntervalIndex.from_tuples(v, closed='both') # you can also use `from_arrays`


df0['Score'] = df1.iloc[idx.get_indexer(df0.Mileage.values), 'Score'].values
df0

  Car  Mileage  Score
0   A        8      3
1   B        6      2
2   C       10      4

概述了创建 IntervalIndex 的其他方法 here

要写入结果,请使用 pd.DataFrame.to_csv -

df0.to_csv('file3.csv')

以下是我在这里所做工作的高级概述。

  1. 首先,读入您的 CSV 文件
  2. 使用pd.IntervalIndex构建区间索引。因此,搜索现在的复杂度是对数的。
  3. 使用idx.get_indexer查找树中每个值的索引
  4. 使用索引在 df1 中定位 Score 值,并将其分配回 df0。注意我调用的是.values,否则赋值回来的时候数值会错位
  5. 将结果写回 CSV

有关 Intervalindex 的更多信息,请查看此 SO Q/A -


请注意 IntervalIndexv0.20 中的新版本,因此如果您使用的是旧版本,请确保使用

更新您的版本
pip install --upgrade pandas

您可以使用 IntervalIndex,新版本 0.20.0+

首先通过read_csv创建数据帧:

df1 = pd.read_csv('file1.csv')
df2 = pd.read_csv('file2.csv')

通过 from_arrays 创建 IntervalIndex:

s = pd.IntervalIndex.from_arrays(df2['Mileage(Min)'], df2['Mileage(Max)'], 'both')

print (s)
IntervalIndex([[1, 3], [4, 6], [7, 9], [10, 12], [13, 15]]
              closed='both',
              dtype='interval[int64]')

Select Mileage 值由 intervalindex 并设置为由 values 创建的数组的新列,因为否则索引未对齐并得到:

TypeError: incompatible index of inserted column with frame index

df1['Score'] = df2.set_index(s).loc[df1['Mileage'], 'Score'].values
print (df1)
  Car  Mileage  Score
0   A        8      3
1   B        6      2
2   C       10      4

最后写入文件的时间为 to_csv:

df1.to_csv('file3.csv', index=False)

设置

data  = [(1,1,3), (2,4,6), (3,7,9), (4,10,12), (5,13,15)]
df = pd.DataFrame(data, columns=['Score','MMin','MMax'])

car_data = [('A', 8), ('B', 6), ('C', 10)]
car = pd.DataFrame(car_data, columns=['Car','Mileage'])

def find_score(x, df):
    result = -99
    for idx, row in df.iterrows():
        if x >= row.MMin and x <= row.MMax:
            result = row.Score
    return result

car['Score'] = car.Mileage.apply(lambda x: find_score(x, df))

产生

In [58]: car
Out[58]:
  Car  Mileage  Score
0   A        8      3
1   B        6      2
2   C       10      4