如何在Pandas数据框架中把字符串转换成整数
让我们看看在Pandas DataFrame中把字符串转换成整数的方法。
方法1:使用Series.astype()方法。
语法: Series.astype(dtype, copy=True, errors=’raise’)
参数:该方法将接受以下参数。
- dtype: 将系列转换为的数据类型。(例如str, float, int)。
- copy: 制作一个数据框架/系列的副本。
- errors: 在转换到无效的数据类型时产生错误。例如,将dict转换成字符串。raise’会引发错误,’ignore’会通过而不引发错误。
返回:系列,数据类型已改变。
最有效的方法之一是Pandas astype()。它是用来修改一组数据类型的。当数据框架从csv文件中创建时,这些列被导入,数据类型被自动配置,有好几次都不是它应该有的类型。例如,一个工资列可能被导入为字符串,但我们必须将其转换为浮点数来进行操作。
示例 1:
# import pandas library
import pandas as pd
# dictionary
Data = {'Name': ['GeeksForGeeks','Python'],
'Unique ID': ['900','450']}
# create a dataframe object
df = pd.DataFrame(Data)
# convert string to an integer
df['Unique ID'] = df['Unique ID'].astype(int)
# show the dataframe
print (df)
print("-"*25)
# show the data types
# of each columns
print (df.dtypes)
输出 :
示例 2:
# import pandas library
import pandas as pd
# dictionary
Data = {'Algorithm': ['Graph', 'Dynamic Programming',
'Number Theory',
' Sorting And Searching'],
'Problems': ['62', '110', '40', '55']}
# create a dataframe object
df = pd.DataFrame(Data)
# convert string to integer
df['Problems'] = df['Problems'].astype(int)
# show the dataframe
print (df)
print("-"*25)
# show the data type
# of each columns
print (df.dtypes)
输出 :
方法2:使用pandas.to_numeric () 方法。
语法: pandas.to_numeric(arg, errors=’raise’, downcast=None)
参数: 这个方法将接受以下参数:
- arg: 列表,元组,1-d数组,或系列。
-
errors: {‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’
**- > ** 如果’raise’,那么无效的解析将引发一个异常。
**- > ** 如果’coerce’,那么无效的解析将被设置为NaN。
**- > ** 如果’忽略’,那么无效的解析将返回输入值。 -
downcast : [default None] 如果不是 “无”,并且如果数据已经成功地投到一个数字dtype中,那么根据以下规则,将产生的数据下移到最小的数字dtype中。
**- > ** ‘整数’或’有符号’:最小的有符号int dtype (min. : np.int8)
**- > ** ‘无符号’:最小的无符号int dtype (min. : np.uint8)
**- > ** ‘float’:最小的float dtype (min. : np.float32)
返回值: numeric if parsing succeeded. Note that 返回值 type depends on input. Series if Series, otherwise ndarray.
pandas.to numeric()是广泛使用的方法之一,以便在Pandas中把参数转换成数字形式。
示例 1:
# import pandas library
import pandas as pd
# dictionary
Data = {'Name': ['GeeksForGeeks','Python'],
'Unique ID': ['900','450']}
# create a dataframe object
df = pd.DataFrame(Data)
# convert integer to string
df['Unique ID'] = pd.to_numeric(df['Unique ID'])
# show the dataframe
print (df)
print("-"*30)
# show the data type
# of each columns
print (df.dtypes)
输出 :
示例 2:
# import pandas library
import pandas as pd
# dictionary
Data = {'Algorithm': ['Graph', 'Dynamic Programming',
'Number Theory',
' Sorting And Searching'],
'Problems': ['62', '110', '40', '55']}
# create a dataframe object
df = pd.DataFrame(Data)
# convert string to an integer
df['Problems'] = pd.to_numeric(df['Problems'])
# show the dataframe
print (df)
print("-"*30)
# show the data type
# of each column
print (df.dtypes)
输出 :