Функции преобразования в Pandas DataFrame

Опубликовано: 28 Марта, 2022

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. In this article, we are using “nba.csv” file to download the CSV, click here.

Cast a pandas object to a specified dtype

DataFrame.astype() function is used to cast a pandas object to a specified dtype. astype() function also provides the capability to convert any suitable existing column to categorical type.

Code #1: Convert the Weight column data type.

# importing pandas as pd
import pandas as pd
  
# Making data frame from the csv file
df = pd.read_csv("nba.csv")
  
# Printing the first 10 rows of 
# the data frame for visualization
  
df[:10]

As the data have some “nan” values so, to avoid any error we will drop all the rows containing any nan values.

# drop all those rows which 
# have any "nan" value in it.
df.dropna(inplace = True)

# let"s find out the data type of Weight column
before = type(df.Weight[0])
  
# Now we will convert it into "int64" type.
df.Weight = df.We<strong>ight.astype("int64")
  
# let"s find out the data type after casting
after = type(df.Weight[0])
  
# print the value of before
before
  
# print the value of after
after

Output:

# print the data frame and see
# what it looks like after the change
df

Вывести лучший тип данных для столбца входного объекта

Функция DataFrame.infer_objects () пытается определить лучший тип данных для столбца входного объекта. Эта функция пытается мягко преобразовать объектно-типизированные столбцы, оставляя неизменными столбцы, не являющиеся объектами, и неконвертируемые столбцы. Правила вывода те же, что и при обычном построении Series / DataFrame.

Code #1: Use infer_objects() function to infer better data type.

# importing pandas as pd
import pandas as pd
  
# Creating the dataframe 
df = pd.DataFrame({"A":["sofia", 5, 8, 11, 100],
                   "B":[2, 8, 77, 4, 11],
                   "C":["amy", 11, 4, 6, 9]})
  
# Print the dataframe
print(df)

Выход :

Let’s see the dtype (data type) of each column in the dataframe.

# to print the basic info
df.info()

As we can see in the output, first and third column is of object type. whereas the second column is of int64 type. Now slice the dataframe and create a new dataframe from it.

# slice from the 1st row till end
df_new = df[1:]
  
# Let"s print the new data frame
df_new
  
# Now let"s print the data type of the columns
df_new.info()

Выход :

As we can see in the output, column “A” and “C” are of object type even though they contain integer value. So, let’s try the infer_objects() function.

# applying infer_objects() function.
df_new = df_new.infer_objects()
  
# Print the dtype after applying the function
df_new.info()

Output :

Now, if we look at the dtype of each column, we can see that the column “A” and “C” are now of int64 type.
 

Detect missing values

Функция DataFrame.isna () используется для обнаружения пропущенных значений. Он возвращает логический объект того же размера, указывающий, являются ли значения NA. Значения NA, такие как None или numpy.NaN, сопоставляются со значениями True. Все остальное сопоставляется со значениями False. Такие символы, как «пустые строки» или numpy.inf не считаются значениями NA (если вы не установите pandas.options.mode.use_inf_as_na = True).

Code #1: Use isna() function to detect the missing values in a dataframe.

# importing pandas as pd
import pandas as pd
  
# Creating the dataframe 
df = pd.read_csv("nba.csv")
  
# Print the dataframe
df

Lets use the isna() function to detect the missing values.

# detect the missing values
df.isna()

Выход :

В выходных данных ячейки, соответствующие отсутствующим значениям, содержат истинное значение, иначе ложное.

Обнаружение существующих / не пропущенных значений

Функция DataFrame.notna () обнаруживает существующие / не пропущенные значения в кадре данных. Функция возвращает логический объект, имеющий тот же размер, что и объект, к которому она применяется, указывая, является ли каждое отдельное значение значением na или нет. Все не пропущенные значения сопоставляются с истиной, а отсутствующие значения сопоставляются с ложью.

Code #1: Use notna() function to find all the non-missing value in the dataframe.

# importing pandas as pd
import pandas as pd
  
# Creating the first dataframe 
df = pd.DataFrame({"A":[14, 4, 5, 4, 1],
                   "B":[5, 2, 54, 3, 2], 
                   "C":[20, 20, 7, 3, 8],
                   "D":[14, 3, 6, 2, 6]})
  
# Print the dataframe
print(df)

Let’s use the dataframe.notna() function to find all the non-missing values in the dataframe.

# find non-na values
df.notna()

Выход :

Как мы видим в выходных данных, все не пропущенные значения в кадре данных были сопоставлены с истиной. Нет ложного значения, так как в фрейме данных нет пропущенного значения.

Способы конвертации в DataFrame

Функция Описание
DataFrame.convert_objects () Попытка вывести лучший dtype для столбцов объекта.
DataFrame.copy () Верните копию индексов и данных этого объекта.
DataFrame.bool () Вернуть bool одного элемента PandasObject.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

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