gpt4 book ai didi

python - 如何将数据框中的字符串转换为浮点值

转载 作者:行者123 更新时间:2023-12-02 05:33:46 25 4
gpt4 key购买 nike

当我们有一列的数据类型为字符串且值如下时,我们会遇到错误列 1 列 21 .89

所以,当我们使用

def azureml_main(dataframe1 = None, dataframe2 = None):

# Execution logic goes here
print('Input pandas.DataFrame #1:')
import pandas as pd
import numpy as np
from sklearn.kernel_approximation import RBFSampler
x =dataframe1.iloc[:,2:1080]
print x
df1 = dataframe1[['colname']]

change = np.array(df1)
b = change.ravel()
print b
rbf_feature = RBFSampler(gamma=1, n_components=100,random_state=1)
print rbf_feature
print "test"
X_features = rbf_feature.fit_transform(x)

在此之后,我们收到错误,因为无法将非 int 转换为 float 类型

最佳答案

使用astype(float)例如:

df['col'] = df['col'].astype(float)

convert_objects :

df = df.convert_objects(convert_numeric=True)

示例:

In [379]:

df = pd.DataFrame({'a':['1.23', '0.123']})
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 0 to 1
Data columns (total 1 columns):
a 2 non-null object
dtypes: object(1)
memory usage: 32.0+ bytes
In [380]:

df['a'].astype(float)
Out[380]:
0 1.230
1 0.123
Name: a, dtype: float64

In [382]:

df = df.convert_objects(convert_numeric=True)
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 0 to 1
Data columns (total 1 columns):
a 2 non-null float64
dtypes: float64(1)
memory usage: 32.0 bytes

更新

如果您运行的是 0.17.0 或更高版本,则 convert_objects 已替换为以下方法:to_numeric , to_datetime ,和to_timestamp所以而不是:

df['col'] = df['col'].astype(float)

你可以这样做:

df['col'] = pd.to_numeric(df['col'])

请注意,默认情况下任何不可转换的值都会引发错误,如果您希望这些值被强制为 NaN 则执行以下操作:

df['col'] = pd.to_numeric(df['col'], errors='coerce')

关于python - 如何将数据框中的字符串转换为浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30121181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com