pinn.xu
中

←︎ Tutorials

Data Processing

2024-10-10 16 min read 3,128 words 中文版

Data processing/cleaning workflows in Pandas: missing values, duplicates, reshaping, joins, aggregations, pivoting, etc.

contents
  1. 1 Handling Missing Values
    1. 1.1 Dropping Missing Values
    2. 1.2 Filling Missing Values
    3. 1.3 Replacing Specific Values
  2. 2 Renaming and Creating Columns
    1. 2.1 Renaming Columns
    2. 2.2 Creating New Columns
  3. 3 Finding Duplicates
  4. 4 Reordering and Reshaping Data
  5. 5 Joining Data
  6. 6 Grouping and Aggregation
  7. 7 Melting and Pivoting
    1. 7.1 Melting Data
    2. 7.2 Pivoting Data
Environment & Versions
python
python==3.12
pandas==2.2.2

1Handling Missing Values

Reading CSV Files:

  • Use pd.read_csv(path) to load a CSV file into a Pandas DataFrame.
  • Ensure path separators use forward slashes / (or escaped backslashes \\ for Win).
python
# import data
import pandas as pd
path = "../../../src/data/beer-and-curry.csv"
df = pd.read_csv(path) # read csv file into a DataFrame
df.head(2) # view first 2 rows
created_atutc_timementionstexturlretweet_countfavorite_countuseruser.locationuser.followers_countuser.friends_countuser.created_atuser.favourites_countuser.verified
006/05/202011:11:49NaNNINE SPICES?????????????????\n?9??SPICE????NIN...https://t.co/wddjIaJTcD24129spices??????????2-1-2 HANROKU??B13820196110/02/2010296False
107/07/202008:08:54@lizzie_hubbard2 @JetsettersFlyin @suziday123 ...Thanks for the invite to join #TravelWinePart...https://t.co/6Z7GgkJE8v617ExpressionsSACape Town South Africa5088528424/06/201115625False

1.1Dropping Missing Values

Use dropna() to remove rows with missing values in the columns required for analysis.

python
# drop rows where 'text' or 'retweet_count' is missing (value is NA or NaN)
df_clean = df.dropna(subset=["text", "retweet_count"])

Dropping Missing Values:

  • Use df.dropna() to remove rows containing missing values (NA or NaN).
  • By default, it removes any row with at least one missing value.
  • Specify subset as a list of column names to only consider missing values in those columns for removal.
  • Use parentheses () or square brackets [] for the subset list.

Note: For data preprocessing, selectively drop rows with missing values only in columns relevant to your analysis to maintain data accuracy.

python
df.shape # view original shape (num of rows, num of cols)
(430, 14)
python
df_clean.shape # shape after dropping rows with missing values
(429, 14)

1.2Filling Missing Values

Use fillna() when a missing value should be replaced rather than removed.

python
# fill missing values in 'mentions' with a placeholder string
df["mentions"] = df["mentions"].fillna("No Mentioned User")

# view replaced values in 'mentions' column
df.head(3)["mentions"]
0                                    No Mentioned User
1    @lizzie_hubbard2 @JetsettersFlyin @suziday123 ...
2    @craftbeerncl! @RidgesideBrewer @Manjitskitche...
Name: mentions, dtype: object

Filling Missing Values:

  • Use df.fillna(value) to replace missing values in a specific column with a placeholder, such as a string.
  • Assign the result back to the column to update the DataFrame.

1.3Replacing Specific Values

Use replace() to convert placeholder values into a more useful representation.

python
# replace the placeholder string with 0
df["mentions"] = df["mentions"].replace("No Mentioned User", 0)

# view replaced values in 'mentions' column
df.head(3)["mentions"]
0                                                    0
1    @lizzie_hubbard2 @JetsettersFlyin @suziday123 ...
2    @craftbeerncl! @RidgesideBrewer @Manjitskitche...
Name: mentions, dtype: object

Replacing Specific Values:

  • Use df.replace(old_value, new_value) to substitute specific values in a column.
  • This is useful for converting placeholders into more appropriate representations, like numbers.

2Renaming and Creating Columns

2.1Renaming Columns

Use rename() to make column names shorter and more descriptive.

python
# rename 'text' to 'content' and 'created_at' to 'date'
df = df.rename(columns={"text": "content", "created_at": "date"})

# view renamed columns
df.head(2)
dateutc_timementionscontenturlretweet_countfavorite_countuseruser.locationuser.followers_countuser.friends_countuser.created_atuser.favourites_countuser.verified
006/05/202011:11:490NINE SPICES?????????????????\n?9??SPICE????NIN...https://t.co/wddjIaJTcD24129spices??????????2-1-2 HANROKU??B13820196110/02/2010296False
107/07/202008:08:54@lizzie_hubbard2 @JetsettersFlyin @suziday123 ...Thanks for the invite to join #TravelWinePart...https://t.co/6Z7GgkJE8v617ExpressionsSACape Town South Africa5088528424/06/201115625False

Renaming Columns:

  • Use df.rename(columns={'old_name': 'new_name'}) to rename columns using a dictionary.
  • This improves readability and descriptiveness.
  • Similarly, use index parameter for renaming indices.

2.2Creating New Columns

Drop rows with missing follower counts before creating derived metrics.

python
# specify specific column(s) to drop rows with missing values
df = df.dropna(subset=["user.followers_count"])

# view cleaned data with no missing follower counts
df.head(2)
dateutc_timementionscontenturlretweet_countfavorite_countuseruser.locationuser.followers_countuser.friends_countuser.created_atuser.favourites_countuser.verified
006/05/202011:11:490NINE SPICES?????????????????\n?9??SPICE????NIN...https://t.co/wddjIaJTcD24129spices??????????2-1-2 HANROKU??B13820196110/02/2010296False
107/07/202008:08:54@lizzie_hubbard2 @JetsettersFlyin @suziday123 ...Thanks for the invite to join #TravelWinePart...https://t.co/6Z7GgkJE8v617ExpressionsSACape Town South Africa5088528424/06/201115625False

Creating New Columns:

  • First, clean the data by dropping rows with missing values in relevant columns using df.dropna(subset=['column']).

Applying Basic Column Operations

Create a new column by applying a vectorized calculation to an existing column.

python
# create a new column 'followers_k' by dividing 'user.followers_count' by 1000
df["followers_k"] = df["user.followers_count"] / 1000

# view the new column alongside the original follower count
df.head(3)[["followers_k", "user.followers_count"]]
followers_kuser.followers_count
03.8203820
15.0885088
20.446446

Creating New Columns:

  • Create new columns by performing vectorized operations on existing columns, e.g., df['new_col'] = df['existing_col'] / 1000.

Applying a Custom Function

Define a reusable function when the transformation is clearer as named logic.

python
# define a function to calculate engagement rate (ER) as a percentage
def calc_er(engagement_count, follower_count):
    return (engagement_count / follower_count) * 100
python
# apply and assign the calculated engagement rate to a new column 'er_rt_fo'
df["er_rt_fo"] = calc_er(
    df["retweet_count"],
    df["user.followers_count"],
)

# view the new engagement rate column alongside the original metrics
df.head(3)[["er_rt_fo", "retweet_count", "user.followers_count"]]
er_rt_foretweet_countuser.followers_count
00.628272243820
10.11792565088
20.8968614446
python
# visualize the relationship between engagement rate & two other metrics
ax = df[["er_rt_fo", "retweet_count", "user.followers_count"]].plot(
    subplots=True,
    title="Engagement Rate vs Retweets and Followers",
)

Creating New Columns:

  • Define a function for complex calculations, such as efficiency ratio: ER = (effective cost / full cost) * 100.
  • Apply the function to DataFrame columns to generate new metrics.
  • Use .values if needed to extract array from Series.
  • Visualize relationships using df.plot() with subplots=True for separate plots, figsize for dimensions, and kind for plot types (default ’line’, options include ‘bar’, ‘hist’, ‘scatter’, ‘pie’).

3Finding Duplicates

Remove fully duplicated rows with duplicated().

python
# drop fully duplicated rows (keep the first occurrence)
# ~ is the negation operator
df = df[~df.duplicated()]

Finding Duplicates:

  • Use df.duplicated() to identify duplicate rows; it returns a boolean Series.
  • Use ~df.duplicated() to keep only unique rows.
  • Specify subset as a list of columns to check for duplicates based on those columns only.
  • Use keep=False to mark all duplicates.

Find users who posted multiple times on the same date by specifying a subset of columns.

python
# find duplicated rows based on 'user' and 'date' columns (keep all occurrences)
df[df.duplicated(subset=["user", "date"], keep=False)].head(2)
dateutc_timementionscontenturlretweet_countfavorite_countuseruser.locationuser.followers_countuser.friends_countuser.created_atuser.favourites_countuser.verifiedfollowers_ker_rt_fo
729/02/202014:42:01@MCRCycleSam @CatrionaSwanson @bricycle @marty...A gathering of UK transport activists; cycle s...https://t.co/OcyyKkhmUh315davelostdavesomewhere459128715/06/200923700False0.4590.653595
1029/02/202023:41:58@CatrionaSwanson @Chris_Boardman @Chris_BoardmanMaybe we could put the spotlight on #Bradford ...https://t.co/0ExO7wr1ld311davelostdavesomewhere459128715/06/200923700False0.4590.653595

4Reordering and Reshaping Data

Sort rows by multiple columns with sort_values().

python
# sort by 'retweet_count' and then by 'user.followers_count' descending
df.sort_values(
    by=["retweet_count", "user.followers_count"],
    ascending=False,
).head(2)
dateutc_timementionscontenturlretweet_countfavorite_countuseruser.locationuser.followers_countuser.friends_countuser.created_atuser.favourites_countuser.verifiedfollowers_ker_rt_fo
006/05/202011:11:490NINE SPICES?????????????????\n?9??SPICE????NIN...https://t.co/wddjIaJTcD24129spices??????????2-1-2 HANROKU??B13820196110/02/2010296False3.8200.628272
107/07/202008:08:54@lizzie_hubbard2 @JetsettersFlyin @suziday123 ...Thanks for the invite to join #TravelWinePart...https://t.co/6Z7GgkJE8v617ExpressionsSACape Town South Africa5088528424/06/201115625False5.0880.117925

Reordering and Reshaping:

  • Use df.sort_values(by=['col1', 'col2'], ascending=False) to sort rows by multiple columns in descending order.
  • Use df.transpose() to swap rows and columns.

Transpose the DataFrame when you need to switch rows and columns for inspection.

python
df.transpose().head(3) # view the DataFrame with rows and columns swapped
0123456789...420421422423424425426427428429
date06/05/202007/07/202031/03/202029/05/202028/11/202001/07/202008/01/202029/02/202003/05/202016/01/2020...10/04/202027/11/202009/12/202025/03/202025/06/202030/12/202030/08/202004/03/202010/08/202007/03/2020
utc_time11:11:4908:08:5413:39:0220:58:1704:46:3706:35:0410:26:3614:42:0117:05:5117:50:08...23:23:2623:31:0923:32:0623:36:0223:38:4123:45:0023:54:1923:55:1923:55:3823:59:42
mentions0@lizzie_hubbard2 @JetsettersFlyin @suziday123 ...@craftbeerncl! @RidgesideBrewer @Manjitskitche...@StCannas @keralankaravan@yooneedmorejodi00@MCRCycleSam @CatrionaSwanson @bricycle @marty...@DrewPritchard@Nellachops73 @MotorheadBeer @CameronsBrewery ......@ashley_collings@101andyhibberd@MariaMo71609443 @jckiker @ScottAdamsSays@lonelyplanet0@Photos_in_Chile@jesshousty @WilliamHousty@beer_porter @siretoknote00

3 rows × 430 columns

5Joining Data

Load a second dataset and combine it with concat().

python
path2 = "../../../src/data/keto-and-vegan.csv"
df2 = pd.read_csv(path2, encoding="latin-1") # load df
df2.head(2) # view first 2 rows
created_atutc_timementionstexturlretweet_countfavorite_countuseruser.locationuser.followers_countuser.friends_countuser.created_atuser.favourites_countuser.verified
001/01/202023:10:27@BioLayneis one of the most respected and unbiased nutr...https://t.co/WDDhoIvXl500Eric_OGreySacramento, CA2333108410/03/201623996False
102/01/202018:16:26@greggprescott1I am O +, which is high protein, than fat, the...https://t.co/1hBpp6MGnu00Glory32XBelgium6366411/07/200922357False

Append matching tables vertically:

python
# concatenate df and df2 vertically (stack rows)
pd.concat([df, df2]).iloc[428:432,] # view row 428 to 431
dateutc_timementionscontenturlretweet_countfavorite_countuseruser.locationuser.followers_countuser.friends_countuser.created_atuser.favourites_countuser.verifiedfollowers_ker_rt_focreated_attext
42810/08/202023:55:380Made the terrible horrible no-good mistake of ...https://t.co/AF23qFRBTv03elizvogtNYC now, Texas forever687110507/03/201139909False0.6870.0NaNNaN
42907/03/202023:59:420This is how I'm celebrating tonight y'all! Bee...https://t.co/Fh7wRYCguR030Rose262Atlanta, GA1776112110/05/200930246False1.7760.0NaNNaN
0NaN23:10:27@BioLayneNaNhttps://t.co/WDDhoIvXl500Eric_OGreySacramento, CA2333108410/03/201623996FalseNaNNaN01/01/2020is one of the most respected and unbiased nutr...
1NaN18:16:26@greggprescott1NaNhttps://t.co/1hBpp6MGnu00Glory32XBelgium6366411/07/200922357FalseNaNNaN02/01/2020I am O +, which is high protein, than fat, the...

Joining Data:

  • Load additional datasets with pd.read_csv() and specify encoding if necessary.
  • Use pd.concat([df1, df2]) to vertically concatenate DataFrames with matching columns.
  • Reset the index with .reset_index(drop=True) to create a continuous index.

Reset the index after concatenation when you want a continuous row index.

python
# concatenate df and df2, then reset the index
pd.concat([df, df2]).reset_index(drop=True).iloc[428:432,]
dateutc_timementionscontenturlretweet_countfavorite_countuseruser.locationuser.followers_countuser.friends_countuser.created_atuser.favourites_countuser.verifiedfollowers_ker_rt_focreated_attext
42810/08/202023:55:380Made the terrible horrible no-good mistake of ...https://t.co/AF23qFRBTv03elizvogtNYC now, Texas forever687110507/03/201139909False0.6870.0NaNNaN
42907/03/202023:59:420This is how I'm celebrating tonight y'all! Bee...https://t.co/Fh7wRYCguR030Rose262Atlanta, GA1776112110/05/200930246False1.7760.0NaNNaN
430NaN23:10:27@BioLayneNaNhttps://t.co/WDDhoIvXl500Eric_OGreySacramento, CA2333108410/03/201623996FalseNaNNaN01/01/2020is one of the most respected and unbiased nutr...
431NaN18:16:26@greggprescott1NaNhttps://t.co/1hBpp6MGnu00Glory32XBelgium6366411/07/200922357FalseNaNNaN02/01/2020I am O +, which is high protein, than fat, the...

6Grouping and Aggregation

Use groupby() with agg() to compute summary statistics by group. The example below calculates total retweets and average follower count for each user.

python
# group by 'user', then aggregate 'retweet_count' with sum 
# and 'user.followers_count' with mean
df_agg = df.groupby("user").agg(
    {"retweet_count": "sum", "user.followers_count": "mean",}
)

# view the aggregated result
df_agg.head(3)
retweet_countuser.followers_count
user
1nnkeeper0557.0
353a9f40f97e4a924440.0
6M70_JET0548.0

Grouping and Aggregation:

  • Use df.groupby('column').agg({'col1': 'sum', 'col2': 'mean'}) to group by a column and compute aggregate statistics.
  • Verify the number of groups using df[~df.duplicated(subset='column')].shape or df['column'].nunique().

You can compare the grouped result with the number of unique users:

python
# count unique users by dropping duplicates based on 'user' column
df[~df.duplicated(subset="user")].shape
(390, 16)
python
# or simply count the number of unique users with nunique()
df["user"].nunique()
390

7Melting and Pivoting

7.1Melting Data

Melting: wide → long

Use melt() to convert wide data into long format for analysis and plotting.

python
# create a sample wide-format DataFrame with pet types and counts
df_wide = pd.DataFrame(
    data=[
        ["cat", 4, 5],
        ["dog", 7, 4],
        ["rabbit", 2, 3],
    ],
    columns=["pet", "male", "female"],
)

df_wide # view it
petmalefemale
0cat45
1dog74
2rabbit23

Without arguments, melt() collapses all columns into variable-value pairs.

python
df_wide.melt() # melt all cols into variable-value pairs (pivot longer)
variablevalue
0petcat
1petdog
2petrabbit
3male4
4male7
5male2
6female5
7female4
8female3

Specify identifier and value columns for a structured long-format result.

python
melted_df = pd.melt(
    df_wide,
    id_vars=["pet"], # keep 'pet' as identifier column
    value_vars=["male", "female"], # value columns
    var_name="sex", # name for the new variable column
    value_name="count", # name for the new value column
)

7.2Pivoting Data

Pivot: long → wide

Pivot the long data back to wide format:

python
df_pivot = melted_df.pivot(
    index="pet", # identifier column becomes index
    columns="sex", # categories in variable column becomes new columns
    values="count", # value column becomes new values
).reset_index() # reset index to turn 'pet' back into a column

df_pivot.columns.name = None # remove the name of the columns index

df_pivot # view the pivoted DataFrame
petfemalemale
0cat54
1dog47
2rabbit32

Use pivot_table() instead of pivot() when there are duplicate index/column combinations, and specify an aggregation function like aggfunc='mean' to summarize duplicates.

For example, if we have duplicate pet entries:

python
# create a sample DataFrame with duplicate pet entries
df_long = pd.DataFrame(
    data=[
        ["cat", "male", 4],
        ["cat", "female", 5],
        ["dog", "female", 7],
        ["dog", "male", 4],
        ["rabbit", "male", 2],
        ["rabbit", "female", 3],
    ],
    columns=["pet", "sex", "count"],
)
df_long # view the long-format DataFrame with duplicates
petsexcount
0catmale4
1catfemale5
2dogfemale7
3dogmale4
4rabbitmale2
5rabbitfemale3

To pivot this long data back to wide format, we can use pivot_table() to handle duplicates:

python
# create a pivot table that averages counts for duplicate entries
(df_long
.pivot_table(
    index="pet",
    columns="sex",
    values="count",
    aggfunc="mean", # average counts for duplicate entries
)
.rename_axis(None, axis=1) # remove the name of the columns headers
.rename_axis(None) # remove the name of the index
)
femalemale
cat5.04.0
dog7.04.0
rabbit3.02.0

↑↓ moveEnter openEsc close or / opens search