Если вы новичок в Pandas, вот наиболее часто используемые функции Pandas, которые помогут вам начать работу с библиотекой Pandas.

Ссылка на документацию pandas здесь

1. Импорт панд

Первое и самое главное - импортировать панд

# Import pandas
import pandas as pd

2. 2 типа наборов данных — Dataframe и Series

В пандах есть 2 типа наборов данных.

Ряд

#To create a series of three different colours
colors = pd.Series(["Red","Blue","Green"])
colors




0      Red
1     Blue
2    Green
dtype: object

кадр данных

#To create a Dataframe of three different car types
cars = pd.DataFrame({"name": ["Nano", "Beetle", "d520"],
                     "make": ["Tata", "Volkswagon", "BMW"],
                     "color": ["Red", "Blue", "Green"]})

cars

Мы можем использовать несколько серий для создания DataFrame.

#To create a Dataframe of three different car types
cars = pd.DataFrame({"name": ["Nano", "Beetle", "d520"],
                     "make": ["Tata", "Volkswagon", "BMW"],
                     "color": colors})

cars

3. Импорт и экспорт из CSV, XLSX

Данные можно считывать из файлов, баз данных или URL-адресов в пандах.

ссылка: https://pandas.pydata.org/docs/reference/io.html#input-output

# Import Data
car_sales = pd.read_csv("car-sales.csv")
car_sales = pd.read_excel("car_sales.xlsx")
car_sales
# Export the DataFrame you created to a .csv file
car_sales.to_csv("exported-car_sales.csv")

4. Узнайте больше о фрейме данных

Эти методы помогут вам лучше понять ваш набор данных

Получить столбцы и индекс

# Get all the column and index values
car_sales.index.values  # array([0, 1, 2, 3, 4, 5, 6])
car_sales.columns.values  # array(['Make', 'Colour', 'Odometer (Miles)', 'Price', 'Rating', 'Seats'], dtype=object)

Типы данных столбцов

# Find the different datatypes of the car data DataFrame
car_sales.dtypes


# result
Make             object
Colour           object
Odometer (KM)     int64
Doors             int64
Price            object
dtype: object

Получить всю информацию о df

# Get information about your DataFrame using info()
car_sales.info()

# result
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 5 columns):
 #   Column         Non-Null Count  Dtype 
---  ------         --------------  ----- 
 0   Make           10 non-null     object
 1   Colour         10 non-null     object
 2   Odometer (KM)  10 non-null     int64 
 3   Doors          10 non-null     int64 
 4   Price          10 non-null     object
dtypes: int64(2), object(3)
memory usage: 528.0+ bytes

5. Основные математические функции

# To know all the basic math values for numbers in the df
car_sales.describe()

# Result
Odometer (KM) Doors
count 10.000000 10.000000
mean 78601.400000 4.000000
std 61983.471735 0.471405
min 11179.000000 3.000000
25% 35836.250000 4.000000
50% 57369.000000 4.000000
75% 96384.500000 4.000000
max 213095.000000 5.000000
# Calling .mean() on a DataFrame
car_prices = pd.Series([3000, 3500, 11250])

car_sales.mean()  # 5916.666666666667
car_sales.sum() # 17750
# Find the mean of the "Odometer (KM)" column in the car sales DataFrame

car_sales["Odometer (KM)"].mean() # 78601.4

Другой интересный метод — `groupby`. который агрегирует данные по одному столбцу и выполняет математические операции. Вы можете проверить это здесь.

# groupby column and sum 
df.groupby(['Animal']).sum()

Ссылка: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html#

6. Просмотр данных

Pandas позволяет нам легко просматривать данные. Вот как

# Find the length of the car sales DataFrame
len(car_sales) # 10
# Show the first 5 rows of the car sales DataFrame
car_sales.head(5)

# Show the bottom 5 rows of the car sales DataFrame
car_sales.tail(5)

# Use .loc to select the row at index 3 of the car sales DataFrame

car_sales.loc[3]

Make                    BMW
Colour                Black
Odometer (KM)         11179
Doors                     5
Price            $22,000.00
Name: 3, dtype: object
# Use .iloc to select the row at position 3 of the car sales DataFrame

car_sales.iloc[3]


Make                    BMW
Colour                Black
Odometer (KM)         11179
Doors                     5
Price            $22,000.00
Name: 3, dtype: object

Проверьте документацию pandas для .loc и .iloc. Подумайте о разных ситуациях, в которых каждый из них может быть использован, и попробуйте их.

# Select the "Odometer (KM)" column from the car sales DataFrame
car_sales["Odometer (KM)"]


0    150043
1     87899
2     32549
3     11179
4    213095
5     99213
6     45698
7     54738
8     60000
9     31600
Name: Odometer (KM), dtype: int64
# Select the rows with over 100,000 kilometers on the Odometer

car_sales[car_sales["Odometer (KM)"] > 100000]

# filter the data with query
car_sales.query('Price > 7000')p

# Create a crosstab of the Make and Doors columns

pd.crosstab(car_sales["Make"], car_sales["Doors"])

# Group columns of the car sales DataFrame by the Make column and find the average
car_sales.groupby(["Make"]).mean()

7. Графики с Matplotlib

Pandas предоставляет мощные инструменты анализа данных и графическое представление данных с помощью Matplotlib.

%matplotlib inline
import matplotlib.pyplot as plt
# Draw a line chart
car_sales["Odometer (KM)"].plot()

# Draw a bar chart
car_sales["Odometer (KM)"].hist()

8. Управление столбцами

Ключевым компонентом библиотеки Pandas является работа с данными.

# Check the changes to the price column
car_sales["Price"] = car_sales["Price"].str.replace('[\$\,\.]', '').astype(int)/100

# Lower the strings of the Make column
car_sales["Make"] = car_sales["Make"].str.lower()

car_sales["Odometer (KM)"] = car_sales["Odometer (KM)"].apply(lambda x: x / 1.6)
car_sales
# Change the title of the Odometer (KM) to represent miles instead of kilometers
car_sales.rename(columns={"Odometer (KM)": "Odometer (Miles)"}, inplace=True)
car_sales

9. Построение новой колонки

# Check out the new DataFrame

car_rating = pd.Series([1,2,3,4,5,2,1])
car_seats = pd.Series([5,5,5,5,7])
car_sales["Rating"] = car_rating
car_sales["Seats"] = car_seats
car_sales

Обратите внимание, что отсутствующие значения представлены как NaN в пандах DataFrames.

10. Работа с отсутствующими данными

# Fill the Odometer column missing values with the mean of the column inplace

car_sales["Seats"].fillna(5,inplace=True)
car_sales

# Remove the rest of the missing data inplace
car_sales.dropna(inplace=True)

11. Отбросьте колонку

Бросайте, если он вам не нужен.

# Remove the last column you added using .drop()
car_sales.drop(['Doors'], axis=1,inplace=True)
car_sales

13. Выберите образец

Мне просто нужен образец из этих данных!! Вот как я это получу

# Shuffle the DataFrame using sample() with the frac parameter set to 1
# Save the the shuffled DataFrame to a new variable
car_sales_shuffled = car_sales.sample(frac=1)
car_sales_shuffled

14. Куда идти дальше?

При этом вы готовы пойти и запачкать руки, работая с наборами данных.

вы можете Объединять, объединять, объединять и сравниватькадры данных https://pandas.pydata.org/docs/user_guide/merging.html?highlight=joins

или Изучите Pivot

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html?highlight=pivot#pandas-dataframe-pivot

Удачного кодирования!!