1. Handling Missing Values
https://www.kaggle.com/code/alexisbcook/handling-missing-values/tutorial
1. 读文件
# modules we'll useimport pandas as pdimport numpy as np# read in all our datanfl_data = pd.read_csv("../input/nflplaybyplay2009to2016/NFL Play by Play 2009-2017 (v4).csv")# set seed for reproducibilitynp.random.seed(0)# np.random.seed(0)的作用:使得随机数据可预测
2. 查看有多少丢失数据
# get the number of missing data points per columnmissing_values_count = nfl_data.isnull().sum()# look at the # of missing points in the first ten columnsmissing_values_count[0:10]
3. 数据丢失率
# how many total missing values do we have?total_cells = np.product(nfl_data.shape)total_missing = missing_values_count.sum()# percent of data that is missingpercent_missing = (total_missing/total_cells) * 100print(percent_missing)
4. 去除缺失值行、列
# remove all the rows that contain a missing valuenfl_data.dropna()
# remove all columns with at least one missing valuecolumns_with_na_dropped = nfl_data.dropna(axis=1)
# just how much data did we lose?print("Columns in original dataset: %d \n" % nfl_data.shape[1])print("Columns with na's dropped: %d" % columns_with_na_dropped.shape[1])
5. 取数据 指定范围的列
# get a small subset of the NFL datasetsubset_nfl_data = nfl_data.loc[:, 'EPA':'Season'].head()subset_nfl_data
6. 用0取代缺失值
# replace all NA's with 0subset_nfl_data.fillna(0)
7. 用缺失值后面的值替换,其他用0
# replace all NA's the value that comes directly after it in the same column,# then replace all the remaining na's with 0subset_nfl_data.fillna(method='bfill', axis=0).fillna(0)
缩放和规范化
1. 包
# modules we'll useimport pandas as pdimport numpy as np# for Box-Cox Transformationfrom scipy import stats# for min_max scalingfrom mlxtend.preprocessing import minmax_scaling# plotting modulesimport seaborn as snsimport matplotlib.pyplot as plt# set seed for reproducibilitynp.random.seed(0)
2. 缩放
# generate 1000 data points randomly drawn from an exponential distributionoriginal_data = np.random.exponential(size=1000)# mix-max scale the data between 0 and 1scaled_data = minmax_scaling(original_data, columns=[0])# plot both together to comparefig, ax = plt.subplots(1, 2, figsize=(15, 3))sns.histplot(original_data, ax=ax[0], kde=True, legend=False)ax[0].set_title("Original Data")sns.histplot(scaled_data, ax=ax[1], kde=True, legend=False)ax[1].set_title("Scaled data")plt.show()
3. 规范化
# normalize the exponential data with boxcoxnormalized_data = stats.boxcox(original_data)# plot both together to comparefig, ax=plt.subplots(1, 2, figsize=(15, 3))sns.histplot(original_data, ax=ax[0], kde=True, legend=False)ax[0].set_title("Original Data")sns.histplot(normalized_data[0], ax=ax[1], kde=True, legend=False)ax[1].set_title("Normalized data")plt.show()
Parsing Dates
1. 包
# modules we'll useimport pandas as pdimport numpy as npimport seaborn as snsimport datetime# read in our datalandslides = pd.read_csv("../input/landslide-events/catalog.csv")# set seed for reproducibilitynp.random.seed(0)
2. parse 时间
# print the first few rows of the date columnprint(landslides['date'].head())

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.
# create a new column, date_parsed, with the parsed dateslandslides['date_parsed'] = pd.to_datetime(landslides['date'], format="%m/%d/%y")
# print the first few rowslandslides['date_parsed'].head()

What if I run into an error with multiple date formats?
landslides['date_parsed'] = pd.to_datetime(landslides['Date'], infer_datetime_format=True)
3. print 对应的月份
# get the day of the month from the date_parsed columnday_of_month_landslides = landslides['date_parsed'].dt.dayday_of_month_landslides.head()
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:
# remove na'sday_of_month_landslides = day_of_month_landslides.dropna()# plot the day of the monthsns.distplot(day_of_month_landslides, kde=False, bins=31)
Character Encodings
https://www.kaggle.com/code/alexisbcook/character-encodings
1. 包
# modules we'll useimport pandas as pdimport numpy as np# helpful character encoding moduleimport chardet# set seed for reproducibilitynp.random.seed(0)
2. 编码和译码
# start with a stringbefore = "This is the euro symbol: €"# encode it to a different encoding, replacing characters that raise errorsafter = before.encode("ascii", errors = "replace")# convert it back to utf-8print(after.decode("ascii"))# We've lost the original underlying byte string! It's been# replaced with the underlying byte string for the unknown character :(
3. Reading in files with encoding problems
# try to read in a file not in UTF-8kickstarter_2016 = pd.read_csv("../input/kickstarter-projects/ks-projects-201612.csv")

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

So chardet is 73% confidence that the right encoding is “Windows-1252”. Let’s see if that’s correct:
# read in the file with the encoding detected by chardetkickstarter_2016 = pd.read_csv("../input/kickstarter-projects/ks-projects-201612.csv", encoding='Windows-1252')# look at the first few lineskickstarter_2016.head()
4. 保存文件到utf-8
# save our file (will be saved as UTF-8 by default!)kickstarter_2016.to_csv("ks-projects-201801-utf8.csv")
Inconsistent Data Entry
1. 包
# modules we'll useimport pandas as pdimport numpy as np# helpful modulesimport fuzzywuzzyfrom fuzzywuzzy import processimport chardet# read in all our dataprofessors = pd.read_csv("../input/pakistan-intellectual-capital/pakistan_intellectual_capital.csv")# set seed for reproducibilitynp.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

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

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

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")
