如果相等,则将数组中的值与数据框中的列进行比较

时间:2019-08-19 15:00:48

标签: python pandas numpy dataframe

我想将DataFrame的列与数组进行比较。如果该列和数组的值相等,则将保存该行和另一列的值到新数组中。

我遇到的问题是,即使有一行,有时也找不到相同数目的行。

import numpy as np
import pandas as pd

input1=np.arange(0.,1.,0.1)
output1=np.arange(1.,0.,-0.1)
df1= pd.DataFrame(columns=['input', 'output'])
df1['input']=input1
df1['output']=output1
in1=np.arange(0.9,0.,-0.1)
in2=np.arange(0.,0.9,0.1)
in_func=np.concatenate((in1, in2), axis=0) 

b=np.zeros((len(in_func)))

for i in range(len(in_func)):
    a = df1.loc[df1['input']==in_func[i], 'output']
    b[i] = a.iloc[0]  #just for explaining my problem

a的输出是:

9    0.1
Name: output, dtype: float64
8    0.2
Name: output, dtype: float64
7    0.3
Name: output, dtype: float64
6    0.4
Name: output, dtype: float64
Series([], Name: output, dtype: float64)
Series([], Name: output, dtype: float64)
Series([], Name: output, dtype: float64)
Series([], Name: output, dtype: float64)
Series([], Name: output, dtype: float64)
0    1.0
Name: output, dtype: float64
1    0.9
Name: output, dtype: float64
2    0.8
Name: output, dtype: float64
3    0.7
Name: output, dtype: float64
4    0.6
Name: output, dtype: float64
5    0.5
Name: output, dtype: float64
6    0.4
Name: output, dtype: float64
7    0.3
Name: output, dtype: float64
8    0.2
Name: output, dtype: float64

我收到错误“ IndexError:单个位置索引器超出范围”,因为in_func=[0.5, 0.4, 0.3, 0.2, 0.1]有一些空序列。我不知道为什么它们为空,这是第二次在in_func中使用此值。

有人可以帮助我吗? 非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

原因是非整数步骤安排没有给出一致的结果。 link

使用非整数步骤(例如0.1)时,结果通常将不一致。在这种情况下,最好使用numpy.linspace。

我运行了一些带有其他打印内容的程序,以使您理解相同的内容。希望这会有所帮助。

import numpy as np
import pandas as pd

in1=np.arange(0.,1.,0.1)
print (in1)
print (in1[0])
print (in1[1])
print (in1[2])
print (in1[3])
print (in1[4])
out1=np.arange(1.,0.,-0.1)
print (out1)

Output :
[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
0.0
0.1
0.2
0.30000000000000004
0.4
[1.  0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1]