我有一个输入DataFrame,我想修改它的一个'Spcx'列,为此我定义了一个升序排序列表'Spaces'
import pandas as pd
import numpy as np
if __name__ == "__main__":
Example = [[ 0],
[ 0],
[0.14],
[0.10],
[0.10],
[0.10],
[0.13],
[0.16],
[0.24],
[0.21],
[0.14],
[0.14]]
Example = pd.DataFrame(data = Example, columns = ['Spcx'])
Spaces = [0, 0.100, 0.125, 0.150, 0.175, 0.200, 0.225, 0.250, 0.275, 0.300]
Spaces = np.array(Spaces) # convert to numpy array
Example["Spcx"] = Spaces[np.searchsorted(Spaces, Example["Spcx"], side = 'left')]
我要找的是每个示例['Spcx']与'空格'的每个间隔进行比较,并取左侧的值,例如:
0 ->空格[0 - 0.100]->0
0.10 ->[0.100 - 0.125] - ->0.100
0.14 ->[0.125 - 0.150] - ->0.125
应该是这样的:
Spcx
0
0
0.125
0.1
0.1
0.1
0.125
0.15
0.225
0.2
0.125
0.125
一种方法是简单地使用side='right'
并减去1:
Spaces = np.array(Spaces) # convert to numpy array
Example["Spcx"] = Spaces[np.searchsorted(Spaces, Example["Spcx"], side='right') - 1]
print(Example)
Spcx
0 0.000
1 0.000
2 0.125
3 0.100
4 0.100
5 0.100
6 0.125
7 0.150
8 0.225
9 0.200
10 0.125
11 0.125
从np.searchsorted
的文档中,假设a
是排序数组,它将返回:
side | 返回的索引I满足 | 左 | (张)& lt;V <= a[i] |
---|---|
对 | a[i-1] <= v <[我] |
您需要numpydigitize
函数:
import pandas as pd
import numpy as np
if __name__ == "__main__":
Example = [[ 0],
[ 0],
[0.14],
[0.10],
[0.10],
[0.10],
[0.13],
[0.16],
[0.24],
[0.21],
[0.14],
[0.14]]
Example = pd.DataFrame(data = Example, columns = ['Spcx'])
Spaces = [0, 0.100, 0.125, 0.150, 0.175, 0.200, 0.225, 0.250, 0.275, 0.300]
Spaces = np.array(Spaces) # convert to numpy array
Example["Spcx"] = Spaces[np.digitize(Example["Spcx"],Spaces)-1]
print(Example)
输出:
Spcx
0 0.000
1 0.000
2 0.125
3 0.100
4 0.100
5 0.100
6 0.125
7 0.150
8 0.225
9 0.200
10 0.125
11 0.125
您可以尝试pd.cut
与right
选项:
Spaces[pd.cut(Example['Spcx'], Spaces, right=False, labels=False)]
输出:
array([0. , 0. , 0.125, 0.1 , 0.1 , 0.1 , 0.125, 0.15 , 0.225,
0.2 , 0.125, 0.125])