Как преобразовать строку в целое число в Pandas DataFrame?
Давайте посмотрим, как преобразовать строку в целое число в Pandas DataFrame:
Метод 1. Использование метода Series.astype () .
Syntax: Series.astype(dtype, copy=True, errors=’raise’)
Parameters: This method will take following parameters:
- dtype: Data type to convert the series into. (for example str, float, int).
- copy: Makes a copy of dataframe/series.
- errors: Error raising on conversion to invalid data type. For example dict to string. ‘raise’ will raise the error and ‘ignore’ will pass without raising error.
Return: Series with changed data type.
Один из самых эффективных подходов - это Pandas astype (). Он используется для изменения набора типов данных. Столбцы импортируются, поскольку фрейм данных создается из файла csv, и тип данных настраивается автоматически, что несколько раз не соответствует требованиям. Например, столбец зарплаты может быть импортирован как строка, но мы должны преобразовать его в число с плавающей запятой для выполнения операций.
Example 1:
Python3
# import pandas libraryimport pandas as pd # dictionaryData = {"Name": ["GeeksForGeeks","Python"], "Unique ID": ["900","450"]} # create a dataframe objectdf = pd.DataFrame(Data) # covert string to an integerdf["Unique ID"] = df["Unique ID"].astype(int) # show the dataframeprint (df)print("-"*25) # show the data types# of each columnsprint (df.dtypes) |
Выход :

Example 2:
Python3
# import pandas libraryimport pandas as pd # dictionaryData = {"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 integerdf["Problems"] = df["Problems"].astype(int) # show the dataframeprint (df)print("-"*25) # show the data type# of each columnsprint (df.dtypes) |
Выход :

Способ 2: Использование панд . to_numeric () метод.
Syntax: pandas.to_numeric(arg, errors=’raise’, downcast=None)
Parameters: This method wil take following parameters:
- arg: list, tuple, 1-d array, or Series.
- errors: {‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’
-> If ‘raise’, then invalid parsing will raise an exception
-> If ‘coerce’, then invalid parsing will be set as NaN
-> If ‘ignore’, then invalid parsing will return the input- downcast: [default None] If not None, and if the data has been successfully cast to a numerical dtype downcast that resulting data to the smallest numerical dtype possible according to the following rules:
-> ‘integer’ or ‘signed’: smallest signed int dtype (min.: np.int8)
-> ‘unsigned’: smallest unsigned int dtype (min.: np.uint8)
-> ‘float’: smallest float dtype (min.: np.float32)Returns: numeric if parsing succeeded. Note that return type depends on input. Series if Series, otherwise ndarray.
pandas.to numeric () - один из широко используемых методов для преобразования аргумента в числовую форму в Pandas.
Example 1:
Python3
# import pandas libraryimport pandas as pd # dictionaryData = {"Name": ["GeeksForGeeks","Python"], "Unique ID": ["900","450"]} # create a dataframe objectdf = pd.DataFrame(Data) # convert integer to string df["Unique ID"] = pd.to_numeric(df["Unique ID"]) # show the dataframeprint (df)print("-"*30) # show the data type# of each columnsprint (df.dtypes) |
Выход :

Example 2:
Python3
# import pandas libraryimport pandas as pd # dictionaryData = {"Algorithm": ["Graph", "Dynamic Programming", "Number Theory", " Sorting And Searching"], "Problems": ["62", "110", "40", "55"]} # create a dataframe objectdf = pd.DataFrame(Data) # convert strint to an integerdf["Problems"] = pd.to_numeric(df["Problems"]) # show the dataframwprint (df)print("-"*30) # show the data type# of each columnprint (df.dtypes) |
Выход :

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.