AIM-PIbd-32-Katysheva-N-E/lab_2/lec2.ipynb
2024-09-28 13:49:26 +03:00

40 KiB
Raw Blame History

Загрузка данных в DataFrame

In [2]:
import pandas as pd

df = pd.read_csv("static\csv\Forbes Billionaires.csv", index_col="PassengerId")

df.info()

print(df.shape)

df.head()
<>:3: SyntaxWarning: invalid escape sequence '\c'
<>:3: SyntaxWarning: invalid escape sequence '\c'
C:\Users\New\AppData\Local\Temp\ipykernel_9568\2466488670.py:3: SyntaxWarning: invalid escape sequence '\c'
  df = pd.read_csv("static\csv\Forbes Billionaires.csv", index_col="PassengerId")
C:\Users\New\AppData\Local\Temp\ipykernel_9568\2466488670.py:3: SyntaxWarning: invalid escape sequence '\c'
  df = pd.read_csv("static\csv\Forbes Billionaires.csv", index_col="PassengerId")
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Cell In[2], line 3
      1 import pandas as pd
----> 3 df = pd.read_csv("static\csv\Forbes Billionaires.csv", index_col="PassengerId")
      5 df.info()
      7 print(df.shape)

File d:\5semestr\AIM\aimvenv\Lib\site-packages\pandas\io\parsers\readers.py:1026, in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, date_format, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options, dtype_backend)
   1013 kwds_defaults = _refine_defaults_read(
   1014     dialect,
   1015     delimiter,
   (...)
   1022     dtype_backend=dtype_backend,
   1023 )
   1024 kwds.update(kwds_defaults)
-> 1026 return _read(filepath_or_buffer, kwds)

File d:\5semestr\AIM\aimvenv\Lib\site-packages\pandas\io\parsers\readers.py:620, in _read(filepath_or_buffer, kwds)
    617 _validate_names(kwds.get("names", None))
    619 # Create the parser.
--> 620 parser = TextFileReader(filepath_or_buffer, **kwds)
    622 if chunksize or iterator:
    623     return parser

File d:\5semestr\AIM\aimvenv\Lib\site-packages\pandas\io\parsers\readers.py:1620, in TextFileReader.__init__(self, f, engine, **kwds)
   1617     self.options["has_index_names"] = kwds["has_index_names"]
   1619 self.handles: IOHandles | None = None
-> 1620 self._engine = self._make_engine(f, self.engine)

File d:\5semestr\AIM\aimvenv\Lib\site-packages\pandas\io\parsers\readers.py:1880, in TextFileReader._make_engine(self, f, engine)
   1878     if "b" not in mode:
   1879         mode += "b"
-> 1880 self.handles = get_handle(
   1881     f,
   1882     mode,
   1883     encoding=self.options.get("encoding", None),
   1884     compression=self.options.get("compression", None),
   1885     memory_map=self.options.get("memory_map", False),
   1886     is_text=is_text,
   1887     errors=self.options.get("encoding_errors", "strict"),
   1888     storage_options=self.options.get("storage_options", None),
   1889 )
   1890 assert self.handles is not None
   1891 f = self.handles.handle

File d:\5semestr\AIM\aimvenv\Lib\site-packages\pandas\io\common.py:873, in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options)
    868 elif isinstance(handle, str):
    869     # Check whether the filename is to be opened in binary mode.
    870     # Binary mode does not support 'encoding' and 'newline'.
    871     if ioargs.encoding and "b" not in ioargs.mode:
    872         # Encoding
--> 873         handle = open(
    874             handle,
    875             ioargs.mode,
    876             encoding=ioargs.encoding,
    877             errors=errors,
    878             newline="",
    879         )
    880     else:
    881         # Binary mode
    882         handle = open(handle, ioargs.mode)

FileNotFoundError: [Errno 2] No such file or directory: 'static\\csv\\Forbes Billionaires.csv'

Получение сведений о пропущенных данных

Типы пропущенных данных:

  • None - представление пустых данных в Python
  • NaN - представление пустых данных в Pandas
  • '' - пустая строка
In [2]:
# Количество пустых значений признаков
print(df.isnull().sum())

print()

# Есть ли пустые значения признаков
print(df.isnull().any())

print()

# Процент пустых значений признаков
for i in df.columns:
    null_rate = df[i].isnull().sum() / len(df) * 100
    if null_rate > 0:
        print(f"{i} процент пустых значений: %{null_rate:.2f}")
Survived      0
Pclass        0
Name          0
Sex           0
Age         177
SibSp         0
Parch         0
Ticket        0
Fare          0
Cabin       687
Embarked      2
dtype: int64

Survived    False
Pclass      False
Name        False
Sex         False
Age          True
SibSp       False
Parch       False
Ticket      False
Fare        False
Cabin        True
Embarked     True
dtype: bool

Age процент пустых значений: %19.87
Cabin процент пустых значений: %77.10
Embarked процент пустых значений: %0.22
In [3]:
fillna_df = df.fillna(0)

print(fillna_df.shape)

print(fillna_df.isnull().any())

# Замена пустых данных на 0
df["AgeFillNA"] = df["Age"].fillna(0)

# Замена пустых данных на медиану
df["AgeFillMedian"] = df["Age"].fillna(df["Age"].median())

df.tail()
(891, 11)
Survived    False
Pclass      False
Name        False
Sex         False
Age         False
SibSp       False
Parch       False
Ticket      False
Fare        False
Cabin       False
Embarked    False
dtype: bool
Out[3]:
Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked AgeFillNA AgeFillMedian
PassengerId
887 0 2 Montvila, Rev. Juozas male 27.0 0 0 211536 13.00 NaN S 27.0 27.0
888 1 1 Graham, Miss. Margaret Edith female 19.0 0 0 112053 30.00 B42 S 19.0 19.0
889 0 3 Johnston, Miss. Catherine Helen "Carrie" female NaN 1 2 W./C. 6607 23.45 NaN S 0.0 28.0
890 1 1 Behr, Mr. Karl Howell male 26.0 0 0 111369 30.00 C148 C 26.0 26.0
891 0 3 Dooley, Mr. Patrick male 32.0 0 0 370376 7.75 NaN Q 32.0 32.0
In [4]:
df["AgeCopy"] = df["Age"]

# Замена данных сразу в DataFrame без копирования
df.fillna({"AgeCopy": 0}, inplace=True)

df.tail()
Out[4]:
Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked AgeFillNA AgeFillMedian AgeCopy
PassengerId
887 0 2 Montvila, Rev. Juozas male 27.0 0 0 211536 13.00 NaN S 27.0 27.0 27.0
888 1 1 Graham, Miss. Margaret Edith female 19.0 0 0 112053 30.00 B42 S 19.0 19.0 19.0
889 0 3 Johnston, Miss. Catherine Helen "Carrie" female NaN 1 2 W./C. 6607 23.45 NaN S 0.0 28.0 0.0
890 1 1 Behr, Mr. Karl Howell male 26.0 0 0 111369 30.00 C148 C 26.0 26.0 26.0
891 0 3 Dooley, Mr. Patrick male 32.0 0 0 370376 7.75 NaN Q 32.0 32.0 32.0

Удаление наблюдений с пропусками

In [5]:
dropna_df = df.dropna()

print(dropna_df.shape)

print(fillna_df.isnull().any())
(183, 14)
Survived    False
Pclass      False
Name        False
Sex         False
Age         False
SibSp       False
Parch       False
Ticket      False
Fare        False
Cabin       False
Embarked    False
dtype: bool

Создание выборок данных

Библиотека scikit-learn

https://scikit-learn.org/stable/index.html

No description has been provided for this image
In [6]:
# Функция для создания выборок
from sklearn.model_selection import train_test_split


def split_stratified_into_train_val_test(
    df_input,
    stratify_colname="y",
    frac_train=0.6,
    frac_val=0.15,
    frac_test=0.25,
    random_state=None,
):
    """
    Splits a Pandas dataframe into three subsets (train, val, and test)
    following fractional ratios provided by the user, where each subset is
    stratified by the values in a specific column (that is, each subset has
    the same relative frequency of the values in the column). It performs this
    splitting by running train_test_split() twice.

    Parameters
    ----------
    df_input : Pandas dataframe
        Input dataframe to be split.
    stratify_colname : str
        The name of the column that will be used for stratification. Usually
        this column would be for the label.
    frac_train : float
    frac_val   : float
    frac_test  : float
        The ratios with which the dataframe will be split into train, val, and
        test data. The values should be expressed as float fractions and should
        sum to 1.0.
    random_state : int, None, or RandomStateInstance
        Value to be passed to train_test_split().

    Returns
    -------
    df_train, df_val, df_test :
        Dataframes containing the three splits.
    """

    if frac_train + frac_val + frac_test != 1.0:
        raise ValueError(
            "fractions %f, %f, %f do not add up to 1.0"
            % (frac_train, frac_val, frac_test)
        )

    if stratify_colname not in df_input.columns:
        raise ValueError("%s is not a column in the dataframe" % (stratify_colname))

    X = df_input  # Contains all columns.
    y = df_input[
        [stratify_colname]
    ]  # Dataframe of just the column on which to stratify.

    # Split original dataframe into train and temp dataframes.
    df_train, df_temp, y_train, y_temp = train_test_split(
        X, y, stratify=y, test_size=(1.0 - frac_train), random_state=random_state
    )

    # Split the temp dataframe into val and test dataframes.
    relative_frac_test = frac_test / (frac_val + frac_test)
    df_val, df_test, y_val, y_test = train_test_split(
        df_temp,
        y_temp,
        stratify=y_temp,
        test_size=relative_frac_test,
        random_state=random_state,
    )

    assert len(df_input) == len(df_train) + len(df_val) + len(df_test)

    return df_train, df_val, df_test
In [7]:
# Вывод распределения количества наблюдений по меткам (классам)
print(df.Pclass.value_counts())

data = df[["Pclass", "Survived", "AgeFillMedian"]].copy()

df_train, df_val, df_test = split_stratified_into_train_val_test(
   data, stratify_colname="Pclass", frac_train=0.60, frac_val=0.20, frac_test=0.20
)

print("Обучающая выборка: ", df_train.shape)
print(df_train.Pclass.value_counts())

print("Контрольная выборка: ", df_val.shape)
print(df_val.Pclass.value_counts())

print("Тестовая выборка: ", df_test.shape)
print(df_test.Pclass.value_counts())
Pclass
3    491
1    216
2    184
Name: count, dtype: int64
Обучающая выборка:  (534, 3)
Pclass
3    294
1    130
2    110
Name: count, dtype: int64
Контрольная выборка:  (178, 3)
Pclass
3    98
1    43
2    37
Name: count, dtype: int64
Тестовая выборка:  (179, 3)
Pclass
3    99
1    43
2    37
Name: count, dtype: int64
In [8]:
from imblearn.over_sampling import ADASYN

ada = ADASYN()

print("Обучающая выборка: ", df_train.shape)
print(df_train.Pclass.value_counts())

X_resampled, y_resampled = ada.fit_resample(df_train, df_train["Pclass"])
df_train_adasyn = pd.DataFrame(X_resampled)

print("Обучающая выборка после oversampling: ", df_train_adasyn.shape)
print(df_train_adasyn.Pclass.value_counts())

df_train_adasyn
Обучающая выборка:  (534, 3)
Pclass
3    294
1    130
2    110
Name: count, dtype: int64
Обучающая выборка после oversampling:  (864, 3)
Pclass
3    294
2    290
1    280
Name: count, dtype: int64
Out[8]:
Pclass Survived AgeFillMedian
0 3 0 28.000000
1 3 0 32.000000
2 3 1 28.000000
3 1 0 45.000000
4 3 0 7.000000
... ... ... ...
859 2 0 26.887761
860 2 1 0.890459
861 2 0 17.481437
862 2 0 17.078473
863 2 1 17.220445

864 rows × 3 columns