如何乘以浮点常量的数据帧列? [英] How do I multiply a dataframe column by a float constant?

查看:138
本文介绍了如何乘以浮点常量的数据帧列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图乘以一个浮动列。如果str(cMachineName)== str(K42):
我有这里的代码:

  df_temp.loc [:,P] * = float((105.0 * 59.0 * math.pi * 0.95 / 1000)/ 3540)

但它给了我这个错误:

  TypeError: int类型的'float'。 

我该如何解决它?

解决方案

我认为问题是一些非数字值,如 45 作为字符串:

解决方案转换为 float int astype

  df_temp = pd.DataFrame({'P':[1,2.5,'45']})

print(df_temp [ 'P']。dtype)
object
$ b df_temp [P] = df_temp [P]。astype(float)
df_temp [P] * float((105.0 * 59.0 * math.pi * 0.95 / 1000)/ 3540)
print(df_temp)
P
0 0.005223
1 0.013057
2 0.235030

另一个问题是像 gh 这样的非数字数据,转换是必要的 to_numeric errors ='coerce'将它们转换为 NaN s:



$ $ $ $ $ $
$($'$ $ $ $ $ $ $ $' 'p'] .dtype)
object
$ b $ df_temp [P] = pd.to_numeric(df_temp [P],errors ='胁迫')
print df_temp)
P
0 1.0
1 2.5
2 NaN

df_temp [P] * = float((105.0 * 59.0 * math。 pi * 0.95 / 1000)/ 3540)
print(df_temp)

P
0 0.005223
1 0.013057
2 Na


I'm trying to multiply a column by a float. I have the code for it here:

if str(cMachineName)==str("K42"):
        df_temp.loc[:, "P"] *= float((105.0* 59.0*math.pi*0.95/1000)/3540)

But it gives me this error:

TypeError: can't multiply sequence by non-int of type 'float'. 

How do I solve it?

解决方案

I think problem is some non numeric values like 45 as string:

Solution is converting to float, int by astype:

df_temp = pd.DataFrame({'P':[1,2.5,'45']})

print (df_temp['P'].dtype)
object

df_temp["P"] = df_temp["P"].astype(float)
df_temp["P"] *= float((105.0* 59.0*math.pi*0.95/1000)/3540)
print (df_temp)
          P
0  0.005223
1  0.013057
2  0.235030

Another problem is non numeric data like gh, for converting is necessary to_numeric with errors='coerce' for converting them to NaNs:

df_temp = pd.DataFrame({'P':[1,2.5,'gh']})

print (df_temp['P'].dtype)
object

df_temp["P"] = pd.to_numeric(df_temp["P"], errors='coerce')
print (df_temp)
     P
0  1.0
1  2.5
2  NaN

df_temp["P"] *= float((105.0* 59.0*math.pi*0.95/1000)/3540)
print (df_temp)

          P
0  0.005223
1  0.013057
2       NaN

这篇关于如何乘以浮点常量的数据帧列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆