Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 理解sqrt的行为-在编写不同的代码时给出不同的结果_Python_Pandas_Null_Series_Sqrt - Fatal编程技术网

Python 理解sqrt的行为-在编写不同的代码时给出不同的结果

Python 理解sqrt的行为-在编写不同的代码时给出不同的结果,python,pandas,null,series,sqrt,Python,Pandas,Null,Series,Sqrt,我有熊猫系列,其编号如下: 0 -1.309176 1 -1.226239 2 -1.339079 3 -1.298509 ... 我试图计算序列中每个数字的平方根 当我尝试整个系列时: s**0.5 >>> 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN .. 10778 NaN 但如果我拿数字来说,它是有效的: -1.309176**0.5 我还尝试从系列中分

我有熊猫系列,其编号如下:

0   -1.309176
1   -1.226239
2   -1.339079
3   -1.298509
...
我试图计算序列中每个数字的平方根

当我尝试整个系列时:

s**0.5
>>>
0       NaN
1       NaN
2       NaN
3       NaN
4       NaN
         ..
10778   NaN
但如果我拿数字来说,它是有效的:

-1.309176**0.5
我还尝试从系列中分割数字:

b1[0]**0.5
>>>
nan
所以我试图理解为什么我写数字时它起作用,但在使用该系列时它不起作用

*这些值是浮点型的:

s.dtype
>>>dtype('float64')

s.to_frame().info()
>>>
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10783 entries, 0 to 10782
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   B1      10783 non-null  float64
dtypes: float64(1)
memory usage: 84.4 KB
s.dtype
>>>数据类型('float64')
s、 至_frame().info()
>>>
范围索引:10783个条目,0到10782
数据列(共1列):
#列非空计数数据类型
---  ------  --------------  -----  
0 B1 10783非空浮点64
数据类型:float64(1)
内存使用率:84.4KB

你不能取一个负数的平方根(如果不尝试复数的话)

>np.sqrt(-1.30)
:1:RuntimeWarning:在sqrt中遇到无效值
楠

当您执行
-1.309176**0.5
时,实际上是在执行
-(1.309176**0.5)
,这是有效的。

这与python中的运算符优先级有关。
**
>一元运算符的优先级
-

>>>1.309176**0.5
-1.144192291531454

>>> (-1.309176)**0.5
(7.006157137165352e-17+1.144192291531454j)
负数的平方根应该是复数。但当您计算
-1.309176**0.5
时,它首先计算
1.309176**0.5
,然后取其负数,因为
**
的优先级为>
-

>>>1.309176**0.5
-1.144192291531454

>>> (-1.309176)**0.5
(7.006157137165352e-17+1.144192291531454j)
现在序列中的数字已经是负数,这不像是对它们进行一元运算,因此这些数字的平方根应该是复数,序列显示为
nan
,因为数据类型是
float

>>> s = pd.Series([-1.30, -1.22])
>>> s
0   -1.30
1   -1.22
dtype: float64
这个系列的平方根给出了
nan

>>> s**0.5
0   NaN
1   NaN
dtype: float64
dtype
更改为
np.complex

>>> s = s.astype(np.complex)
>>> s
0   -1.300000+0.000000j
1   -1.220000+0.000000j
dtype: complex128
现在你得到s的平方根

>>> s**0.05
0    1.000730+0.158500j
1    0.997557+0.157998j
dtype: complex128

什么是
s.to_frame().info()
?这似乎是同一个数据相关的问题。这是关于运算符优先级的问题。可能会有帮助。您确定您的系列具有数字数据类型吗?
s.dtype
显示了什么?@jezrael在后面加了一句。第一句是试图取负数的平方根,第二句是取正数的平方根,使之为负数