了解pandas数据帧中的数学错误

use*_*387 5 python ipython pandas

我正在尝试从其他列的pandas数据框中生成一个新列,并且我得到一些我不理解的数学错误.这是问题的快照和一些简化的诊断......

我可以生成一个看起来很不错的数据框:

import pandas
import math as m

data = {'loc':['1','2','3','4','5'],
        'lat':[61.3850,32.7990,34.9513,14.2417,33.7712],
        'lng':[-152.2683,-86.8073,-92.3809,-170.7197,-111.3877]}
frame = pandas.DataFrame(data)

frame

Out[15]:
lat lng loc
0    61.3850    -152.2683    1
1    32.7990     -86.8073    2
2    34.9513     -92.3809    3
3    14.2417    -170.7197    4
4    33.7712    -111.3877    5
5 rows × 3 columns
Run Code Online (Sandbox Code Playgroud)

我可以做简单的数学运算(即度数到弧度):

In [32]:
m.pi*frame.lat/180.

Out[32]:
0    1.071370
1    0.572451
2    0.610015
3    0.248565
4    0.589419
Name: lat, dtype: float64
Run Code Online (Sandbox Code Playgroud)

但是我无法使用python数学库从度数转换为弧度:

 In [33]:
 m.radians(frame.lat)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-99a986252f80> in <module>()
----> 1 m.radians(frame.lat)

/Users/user/anaconda/lib/python2.7/site-packages/pandas/core/series.pyc in wrapper(self)
     72             return converter(self.iloc[0])
     73         raise TypeError(
---> 74             "cannot convert the series to {0}".format(str(converter)))
     75     return wrapper
     76 

TypeError: cannot convert the series to <type 'float'>
Run Code Online (Sandbox Code Playgroud)

并且甚至无法将值转换为浮点数以尝试强制它工作:

In [34]:

float(frame.lat)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-34-3311aee92f31> in <module>()
----> 1 float(frame.lat)

/Users/user/anaconda/lib/python2.7/site-packages/pandas/core/series.pyc in wrapper(self)
     72             return converter(self.iloc[0])
     73         raise TypeError(
---> 74             "cannot convert the series to {0}".format(str(converter)))
     75     return wrapper
     76 

TypeError: cannot convert the series to <type 'float'>
Run Code Online (Sandbox Code Playgroud)

我确信必须有一个简单的解释,并感谢你帮助我找到它.谢谢!

unu*_*tbu 8

math.radians等数学函数需要一个数值,如float,而不是像a这样的序列pandas.Series.

相反,您可以使用numpy.radians,因为numpy.radians可以接受数组作为输入:

In [95]: np.radians(frame['lat'])
Out[95]: 
0    1.071370
1    0.572451
2    0.610015
3    0.248565
4    0.589419
Name: lat, dtype: float64
Run Code Online (Sandbox Code Playgroud)

只有长度为1的系列可以转换为a float.所以虽然这有效,

In [103]: math.radians(pd.Series([1]))
Out[103]: 0.017453292519943295
Run Code Online (Sandbox Code Playgroud)

一般来说它不会:

In [104]: math.radians(pd.Series([1,2]))
TypeError: cannot convert the series to <type 'float'>
Run Code Online (Sandbox Code Playgroud)

math.radians正在呼吁float其论点.请注意,调用float时会出现相同的错误pd.Series([1,2]):

In [105]: float(pd.Series([1,2]))
TypeError: cannot convert the series to <type 'float'>
Run Code Online (Sandbox Code Playgroud)