1. Handling Missing Values

https://www.kaggle.com/code/alexisbcook/handling-missing-values/tutorial

1. 读文件

  1. # modules we'll use
  2. import pandas as pd
  3. import numpy as np
  4. # read in all our data
  5. nfl_data = pd.read_csv("../input/nflplaybyplay2009to2016/NFL Play by Play 2009-2017 (v4).csv")
  6. # set seed for reproducibility
  7. np.random.seed(0)
  8. # np.random.seed(0)的作用:使得随机数据可预测

2. 查看有多少丢失数据

  1. # get the number of missing data points per column
  2. missing_values_count = nfl_data.isnull().sum()
  3. # look at the # of missing points in the first ten columns
  4. missing_values_count[0:10]

3. 数据丢失率

  1. # how many total missing values do we have?
  2. total_cells = np.product(nfl_data.shape)
  3. total_missing = missing_values_count.sum()
  4. # percent of data that is missing
  5. percent_missing = (total_missing/total_cells) * 100
  6. print(percent_missing)

4. 去除缺失值行、列

  1. # remove all the rows that contain a missing value
  2. nfl_data.dropna()
  1. # remove all columns with at least one missing value
  2. columns_with_na_dropped = nfl_data.dropna(axis=1)
  1. # just how much data did we lose?
  2. print("Columns in original dataset: %d \n" % nfl_data.shape[1])
  3. print("Columns with na's dropped: %d" % columns_with_na_dropped.shape[1])

5. 取数据 指定范围的列

  1. # get a small subset of the NFL dataset
  2. subset_nfl_data = nfl_data.loc[:, 'EPA':'Season'].head()
  3. subset_nfl_data

6. 用0取代缺失值

  1. # replace all NA's with 0
  2. subset_nfl_data.fillna(0)

7. 用缺失值后面的值替换,其他用0

  1. # replace all NA's the value that comes directly after it in the same column,
  2. # then replace all the remaining na's with 0
  3. subset_nfl_data.fillna(method='bfill', axis=0).fillna(0)

缩放和规范化

1. 包

  1. # modules we'll use
  2. import pandas as pd
  3. import numpy as np
  4. # for Box-Cox Transformation
  5. from scipy import stats
  6. # for min_max scaling
  7. from mlxtend.preprocessing import minmax_scaling
  8. # plotting modules
  9. import seaborn as sns
  10. import matplotlib.pyplot as plt
  11. # set seed for reproducibility
  12. np.random.seed(0)

2. 缩放

  1. # generate 1000 data points randomly drawn from an exponential distribution
  2. original_data = np.random.exponential(size=1000)
  3. # mix-max scale the data between 0 and 1
  4. scaled_data = minmax_scaling(original_data, columns=[0])
  5. # plot both together to compare
  6. fig, ax = plt.subplots(1, 2, figsize=(15, 3))
  7. sns.histplot(original_data, ax=ax[0], kde=True, legend=False)
  8. ax[0].set_title("Original Data")
  9. sns.histplot(scaled_data, ax=ax[1], kde=True, legend=False)
  10. ax[1].set_title("Scaled data")
  11. plt.show()

image.png

3. 规范化

  1. # normalize the exponential data with boxcox
  2. normalized_data = stats.boxcox(original_data)
  3. # plot both together to compare
  4. fig, ax=plt.subplots(1, 2, figsize=(15, 3))
  5. sns.histplot(original_data, ax=ax[0], kde=True, legend=False)
  6. ax[0].set_title("Original Data")
  7. sns.histplot(normalized_data[0], ax=ax[1], kde=True, legend=False)
  8. ax[1].set_title("Normalized data")
  9. plt.show()

image.png

Parsing Dates

1. 包

  1. # modules we'll use
  2. import pandas as pd
  3. import numpy as np
  4. import seaborn as sns
  5. import datetime
  6. # read in our data
  7. landslides = pd.read_csv("../input/landslide-events/catalog.csv")
  8. # set seed for reproducibility
  9. np.random.seed(0)

2. parse 时间

  1. # print the first few rows of the date column
  2. print(landslides['date'].head())

image.png
Yep, those are dates! But just because I, a human, can tell that these are dates doesn’t mean that Python knows that they’re dates. Notice that at the bottom of the output of head(), you can see that it says that the data type of this column is “object”.
Convert our date columns to datetime
Some examples:

  • 1/17/07 has the format “%m/%d/%y”
  • 17-1-2007 has the format “%d-%m-%Y”

the most common are %d for day, %m for month, %y for a two-digit year and %Y for a four digit year.

  1. # create a new column, date_parsed, with the parsed dates
  2. landslides['date_parsed'] = pd.to_datetime(landslides['date'], format="%m/%d/%y")
  1. # print the first few rows
  2. landslides['date_parsed'].head()

image.png
What if I run into an error with multiple date formats?

  1. landslides['date_parsed'] = pd.to_datetime(landslides['Date'], infer_datetime_format=True)

3. print 对应的月份

  1. # get the day of the month from the date_parsed column
  2. day_of_month_landslides = landslides['date_parsed'].dt.day
  3. day_of_month_landslides.head()

image.png

4. Plot the day of the month to check the date parsing

let’s plot a histogram of the days of the month. We expect it to have values between 1 and 31 and, since there’s no reason to suppose the landslides are more common on some days of the month than others, a relatively even distribution. (With a dip on 31 because not all months have 31 days.) Let’s see if that’s the case:

  1. # remove na's
  2. day_of_month_landslides = day_of_month_landslides.dropna()
  3. # plot the day of the month
  4. sns.distplot(day_of_month_landslides, kde=False, bins=31)

image.png

Character Encodings

https://www.kaggle.com/code/alexisbcook/character-encodings

1. 包

  1. # modules we'll use
  2. import pandas as pd
  3. import numpy as np
  4. # helpful character encoding module
  5. import chardet
  6. # set seed for reproducibility
  7. np.random.seed(0)

2. 编码和译码

  1. # start with a string
  2. before = "This is the euro symbol: €"
  3. # encode it to a different encoding, replacing characters that raise errors
  4. after = before.encode("ascii", errors = "replace")
  5. # convert it back to utf-8
  6. print(after.decode("ascii"))
  7. # We've lost the original underlying byte string! It's been
  8. # replaced with the underlying byte string for the unknown character :(

image.png

3. Reading in files with encoding problems

  1. # try to read in a file not in UTF-8
  2. kickstarter_2016 = pd.read_csv("../input/kickstarter-projects/ks-projects-201612.csv")

image.png

  1. # look at the first ten thousand bytes to guess the character encoding
  2. with open("../input/kickstarter-projects/ks-projects-201801.csv", 'rb') as rawdata:
  3. result = chardet.detect(rawdata.read(10000))
  4. # check what the character encoding might be
  5. print(result)

image.png
So chardet is 73% confidence that the right encoding is “Windows-1252”. Let’s see if that’s correct:

  1. # read in the file with the encoding detected by chardet
  2. kickstarter_2016 = pd.read_csv("../input/kickstarter-projects/ks-projects-201612.csv", encoding='Windows-1252')
  3. # look at the first few lines
  4. kickstarter_2016.head()

4. 保存文件到utf-8

  1. # save our file (will be saved as UTF-8 by default!)
  2. kickstarter_2016.to_csv("ks-projects-201801-utf8.csv")

Inconsistent Data Entry

1. 包

  1. # modules we'll use
  2. import pandas as pd
  3. import numpy as np
  4. # helpful modules
  5. import fuzzywuzzy
  6. from fuzzywuzzy import process
  7. import chardet
  8. # read in all our data
  9. professors = pd.read_csv("../input/pakistan-intellectual-capital/pakistan_intellectual_capital.csv")
  10. # set seed for reproducibility
  11. np.random.seed(0)

2. 大小写不一致

# get all the unique values in the 'Country' column
countries = professors['Country'].unique()

# sort them alphabetically and then take a closer look
countries.sort()
countries

image.png
I can see some problems due to inconsistent data entry: ‘ Germany’, and ‘germany’, for example, or ‘ New Zealand’ and ‘New Zealand’.

# convert to lower case
professors['Country'] = professors['Country'].str.lower()
# remove trailing white spaces
professors['Country'] = professors['Country'].str.strip()

3. Use fuzzy matching to correct inconsistent data entry

# get all the unique values in the 'Country' column
countries = professors['Country'].unique()

# sort them alphabetically and then take a closer look
countries.sort()
countries

image.png
It does look like there is another inconsistency: ‘southkorea’ and ‘south korea’ should be the same.

# get the top 10 closest matches to "south korea"
matches = fuzzywuzzy.process.extract("south korea", countries, limit=10, scorer=fuzzywuzzy.fuzz.token_sort_ratio)

# take a look at them
matches

image.png
We can see that two of the items in the cities are very close to “south korea”: “south korea” and “southkorea”. Let’s replace all rows in our “Country” column that have a ratio of > 47 with “south korea”.

# function to replace rows in the provided column of the provided dataframe
# that match the provided string above the provided ratio with the provided string
def replace_matches_in_column(df, column, string_to_match, min_ratio = 47):
    # get a list of unique strings
    strings = df[column].unique()

    # get the top 10 closest matches to our input string
    matches = fuzzywuzzy.process.extract(string_to_match, strings, 
                                         limit=10, scorer=fuzzywuzzy.fuzz.token_sort_ratio)

    # only get matches with a ratio > 90
    close_matches = [matches[0] for matches in matches if matches[1] >= min_ratio]

    # get the rows of all the close matches in our dataframe
    rows_with_matches = df[column].isin(close_matches)

    # replace all rows with close matches with the input matches 
    df.loc[rows_with_matches, column] = string_to_match

    # let us know the function's done
    print("All done!")
# use the function we just wrote to replace close matches to "south korea" with "south korea"
replace_matches_in_column(df=professors, column='Country', string_to_match="south korea")