'df.iloc causes error when used to perform second calculation
I am opening a .csv file and pulling it into a pandas dataframe (in this case there are 87 rows, 0-86). I want to perform separate calculations with the contents of the first and last row, so I create two separate df from the original.
df=pd.DataFrame(data, columns=['SOLE','SOLN','EOLE','EOLN'])
df1=df.iloc[:1] #first row
df2=df.iloc[-1:] #Last row
I then perform some basic trigonometry functions. The calculations work, I have replaced df1/df2['SOLE'] parts with a hardcoded number and get a result.
BGO_Eraw=(df1['SOLE']-SOL_Orig_Distance*np.sin(Line_Head+SOL_Orig_Angle)) # BG Origin E coordinate
BRC_Eraw=(df2['SOLE']+SOL_Orig_Distance*np.sin((Line_Head-SOL_Orig_Angle)+np.pi)) # BRC_E coordinate
Printing df1, df2, BGO_Eraw & BRC_Eraw I get:
SOLE SOLN EOLE EOLN
0 525182.75 6756568.136 528470.372 6764562.356
SOLE SOLN EOLE EOLN
86 527171.168 6755750.399 530458.79 6763744.619
0 525170.001
dtype: float64
0 NaN
86 NaN
dtype: float64
Why am I seeing two parts (0 & 86) for BRC but only one for BGO? If I swap which df gets the first and last row .i.e. df1=df.iloc[-1:], I still get the same problem, it is the second calculation (BRC) that throws up the double NaN.
The csv file looks like this:
Line #,Name,SOLE,SOLN,EOLE,EOLN,SOLKP,EOLKP
1,EQ22307-01001-04,525182.750,6756568.136,528470.372,6764562.356,0.000,8.644
2,EQ22307-01005-08,525205.871,6756558.628,528493.493,6764552.848,0.000,8.644
3,EQ22307-01009-12,525228.992,6756549.119,528516.614,6764543.339,0.000,8.644
4,EQ22307-01013-16,525252.113,6756539.610,528539.735,6764533.830,0.000,8.644
5,EQ22307-01017-20,525275.234,6756530.102,528562.856,6764524.322,0.000,8.644
6,EQ22307-01021-24,525298.355,6756520.593,528585.977,6764514.813,0.000,8.644
Solution 1:[1]
Given Random values for the variables we don't know, this should work fine:
# No idea what these are:
SOL_Orig_Distance = 1
Line_Head = 2
SOL_Orig_Angle = 3
BGO_Eraw = lambda row: row.SOLE-SOL_Orig_Distance*np.sin(Line_Head+SOL_Orig_Angle)
BRC_Eraw = lambda row: row.SOLE+SOL_Orig_Distance*np.sin((Line_Head-SOL_Orig_Angle)+np.pi)
pd.concat([df.iloc[:1].apply(BGO_Eraw, axis=1), df.iloc[-1:].apply(BRC_Eraw, axis=1)])
Output:
0 525183.708924
5 525299.196471
dtype: float64
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | BeRT2me |