如何在Pandas DataFrame中把字符串转换成浮点数
在这篇文章中,我们将看看在pandas数据框架中把字符串转换成浮点数的不同方法。现在,让我们创建一个以 “年份 “和 “通货膨胀率 “为列的数据框架。
# importing pandas library
import pandas as pd
# dictionary
Data = {'Year': ['2016', '2017',
'2018', '2019'],
'Inflation Rate': ['4.47', '5',
'5.98', '4.1']}
# create a dataframe
df = pd.DataFrame(Data)
# show the dataframe
print (df)
# show the datatypes
print(df.dtypes)
输出:
方法1:使用 DataFrame.astype()
该方法用于将一个pandas对象转换为一个指定的dtype。
语法: DataFrame.astype(self: ~ FrameOrSeries, dtype, copy: bool = True, errors: str = ‘raise’)
返回: casted:调用者的类型
例子:在这个例子中,我们将把 “通货膨胀率 “列的每个值转换成浮点数。
# importing pandas library
import pandas as pd
# dictionary
Data = {'Year': ['2016', '2017',
'2018', '2019'],
'Inflation Rate': ['4.47', '5',
'5.98', '4.1']}
# create a dataframe
df = pd.DataFrame(Data)
# converting each value
# of column to a string
df['Inflation Rate'] = df['Inflation Rate'].astype(float)
# show the dataframe
print(df)
# show the datatypes
print (df.dtypes)
输出:
方法二:使用 pandas.to_numeric() **函数。
该函数用于将参数转换为数字类型。
语法: pandas.to_numeric(arg, errors=’raise’, downcast=None)
例子1:在这个例子中,我们将把 “通货膨胀率 “列的每个值转换成浮点数。
代码:
# importing pandas library
import pandas as pd
# creating a dictionary
Data = {'Year': ['2016', '2017',
'2018', '2019'],
'Inflation Rate': ['4.47', '5',
'5.98', '4.1']}
# create a dataframe
df = pd.DataFrame(Data)
# converting each value of column to a string
df['Inflation Rate'] = pd.to_numeric(df['Inflation Rate'])
# show the dataframe
print(df)
# show the data types
print (df.dtypes)
输出:
例子2:有时,我们可能没有把浮动值表示成字符串。所以,pd.to_numeric()函数会显示一个错误。为了消除这个错误,我们可以使用errors=’coerce’ ,将这个位置的值转换为NaN。
代码 :
# importing pandas as pd
import pandas as pd
# dictionary
Data = {'Year': ['2016', '2017',
'2018', '2019'],
'Inflation Rate': ['4.47', '5',
'No data', '4.1']}
# create a dataframe
df = pd.DataFrame(Data)
# converting each value of column to a string
df['Inflation Rate'] = pd.to_numeric(df['Inflation Rate'],
errors = 'coerce')
# show the dataframe
print(df)
# show the data types
print (df.dtypes)
输出:
注意:字符串数据类型显示为对象。