如何将 Pandas 列转换为 for 循环的两倍?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48328970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert pandas columns to double in for loop?
提问by Cody
I have a pandas dataframe called df10
.
我有一个名为 .pandas 的数据框df10
。
cols10 = list(df10.columns)
I want to change the data type to double
where the column name starts with "m_"
我想将数据类型更改double
为列名开头的位置"m_"
for param in cols10:
if param.startswith("m_"):
df10[[param]] = df10[[param]].apply(pd.to_double)
However, I'm getting this error:
但是,我收到此错误:
AttributeError: 'module' object has no attribute 'to_double'
回答by Haleemur Ali
the function to_double
doesn't exist in pandas. pandas datatypes are essentially numpy data types
该功能to_double
在Pandas中不存在。pandas 数据类型本质上是numpy 数据类型
i'm assuming you mean float64 by double
我假设你的意思是 float64 by double
you can either let numpy decide the precision for you
你可以让 numpy 为你决定精度
for col in cols10:
if col.startswith('m_'):
df[col] = df[col].astype(float)
or specify the precision yourself
或自己指定精度
for col in cols10:
if col.startswith('m_'):
df[col] = df[col].astype(np.float64) # or np.float32 or np.float16
回答by Vaishali
You can do this without loop,
你可以在没有循环的情况下做到这一点,
reqd_cols = df10.columns[df10.columns.str.startswith('m_')]
df10[reqd_cols] = df10[reqd_cols].astype('float64')
回答by pault
Use the astype()
function to convert the column to float
(python doesn't have a double
type like C).
使用该astype()
函数将列转换为float
(python 没有double
像 C这样的类型)。
cols10 = [c for c in df10 if c.startswith("m_")]
df10.loc[:, cols10 ] = df10.loc[:, cols10].astype(float)
This approach is faster than using a for
loop, but if you insist on looping over the columns:
这种方法比使用for
循环更快,但如果您坚持循环遍历列:
cols10 = [c for c in df10 if c.startswith("m_")]
for param in cols10:
df10[param] = df10[param].astype(float)
More on floating point numbers here:
更多关于这里的浮点数:
Floating point numbers are usually implemented using double in C
浮点数通常在 C 中使用 double 实现