pinn.xu
EN

←︎ 数据可视化教程

数据清理

2024-10-10 17 分钟读完 3,924 字 English

Pandas 数据处理与清洗流程:缺失值、重复值、数据重塑、表连接、分组聚合、透视表等。

目录
  1. 1 处理缺失值
    1. 1.1 删除缺失值
    2. 1.2 填充缺失值
    3. 1.3 替换特定值
  2. 2 重命名和创建列
    1. 2.1 重命名列
    2. 2.2 创建新列
  3. 3 查找重复值
  4. 4 重新排序和重塑数据
  5. 5 连接数据
  6. 6 分组和聚合
  7. 7 Melt 和 Pivot
    1. 7.1 Melt 数据
    2. 7.2 Pivot 数据
环境与版本
python
python==3.12
pandas==2.2.2

1处理缺失值

读取 CSV 文件:

  • 使用 pd.read_csv(path) 将 CSV 文件读取为 Pandas DataFrame。
  • 文件路径中的分隔符建议使用正斜杠 /(Windows 中也可以使用转义反斜杠 \\)。
python
# 导入数据
import pandas as pd
path = "../../../src/data/beer-and-curry.csv"
df = pd.read_csv(path) # 将 CSV 文件读取为 DataFrame
df.head(2) # 查看前 2 行
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.1删除缺失值

当分析所需的列中存在缺失值时,可以使用 dropna() 删除对应行。

python
# 删除 'text' 或 'retweet_count' 缺失(值为 NA 或 NaN)的行
df_clean = df.dropna(subset=["text", "retweet_count"])

删除缺失值:

  • 使用 df.dropna() 删除包含缺失值(NA 或 NaN)的行。
  • 默认情况下,只要某一行中至少有一个缺失值,该行就会被删除。
  • 可以通过 subset 指定列名列表,只根据这些列中的缺失值来决定是否删除整行。
  • subset 的列名集合可以使用圆括号 () 或方括号 []。

注意: 数据预处理时,通常不需要直接删除所有包含缺失值的行。更稳妥的做法是只针对分析所需的关键列删除缺失值,以尽量保持数据准确性。

python
df.shape # 查看原始形状(行数和列数)
(430, 14)
python
df_clean.shape # 删除缺失值后的形状
(429, 14)

1.2填充缺失值

当缺失值应该被替换而不是删除时,可以使用 fillna()。

python
# 用占位字符串填充 'mentions' 中的缺失值
df["mentions"] = df["mentions"].fillna("No Mentioned User")

# 查看 'mentions' 列中替换后的值
df.head(3)["mentions"]
0                                    No Mentioned User
1    @lizzie_hubbard2 @JetsettersFlyin @suziday123 ...
2    @craftbeerncl! @RidgesideBrewer @Manjitskitche...
Name: mentions, dtype: object

填充缺失值:

  • 使用 df.fillna(value) 将某一列中的缺失值替换为指定占位值,例如字符串。
  • 如果需要更新原 DataFrame,需要将结果重新赋值回该列。

1.3替换特定值

使用 replace() 可以将占位值转换为更适合后续分析的表示方式。

python
# 将占位字符串替换为 0
df["mentions"] = df["mentions"].replace("No Mentioned User", 0)

# 查看 'mentions' 列中替换后的值
df.head(3)["mentions"]
0                                                    0
1    @lizzie_hubbard2 @JetsettersFlyin @suziday123 ...
2    @craftbeerncl! @RidgesideBrewer @Manjitskitche...
Name: mentions, dtype: object

替换特定值:

  • 使用 df.replace(old_value, new_value) 替换某一列中的特定值。
  • 这常用于将占位字符串转换为更合适的形式,例如数字。

2重命名和创建列

2.1重命名列

使用 rename() 可以让列名更简短、更清晰。

python
# 将 'text' 重命名为 'content',将 'created_at' 重命名为 'date'
df = df.rename(columns={"text": "content", "created_at": "date"})

# 查看重命名后的列
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

重命名列:

  • 使用 df.rename(columns={'old_name': 'new_name'}) 通过字典重命名列。
  • 这可以提高数据表的可读性和描述性。
  • 类似地,也可以使用 index 参数重命名索引。

2.2创建新列

在创建衍生指标前,先删除粉丝数缺失的行。

python
# 指定特定列,用于删除含缺失值的行
df = df.dropna(subset=["user.followers_count"])

# 查看已清理的数据,其中粉丝数没有缺失值
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

创建新列:

  • 首先使用 df.dropna(subset=['column']) 清理相关列中的缺失值。

对现有列进行基础运算

可以对现有列进行向量化计算,并将结果保存为新列。

python
# 通过将 'user.followers_count' 除以 1000 创建新列 'followers_k'
df["followers_k"] = df["user.followers_count"] / 1000

# 同时查看新列和原始粉丝数
df.head(3)[["followers_k", "user.followers_count"]]
followers_kuser.followers_count
03.8203820
15.0885088
20.446446

创建新列:

  • 可以通过对现有列进行向量化运算创建新列,例如 df['new_col'] = df['existing_col'] / 1000。

应用自定义函数

当转换逻辑用命名函数表达更清晰时,可以先定义可复用函数。

python
# 定义函数,用于计算百分比形式的互动率(Engagement Rate: ER)
def calc_er(engagement_count, follower_count):
    return (engagement_count / follower_count) * 100
python
# 应用计算出的互动率,并赋值给新列 'er_rt_fo'
df["er_rt_fo"] = calc_er(
    df["retweet_count"],
    df["user.followers_count"],
)

# 同时查看新的互动率列和原始指标
df.head(3)[["er_rt_fo", "retweet_count", "user.followers_count"]]
er_rt_foretweet_countuser.followers_count
00.628272243820
10.11792565088
20.8968614446
python
# 可视化互动率与另外两个指标之间的关系
ax = df[["er_rt_fo", "retweet_count", "user.followers_count"]].plot(
    subplots=True,
    title="Engagement Rate vs Retweets and Followers",
)

创建新列:

  • 对于更复杂的计算,可以先定义函数,例如效率比率:ER = (effective cost / full cost) * 100。
  • 将函数应用到 DataFrame 的列上,即可生成新的指标列。
  • 如有需要,可以使用 .values 从 Series 中提取数组值。
  • 可以使用 df.plot() 进行快速可视化;subplots=True 会生成分面图,figsize 控制尺寸,kind 控制图形类型(默认是 'line',也可以使用 'bar'、'hist'、'scatter'、'pie')。

3查找重复值

使用 duplicated() 删除完全重复的行。

python
# 删除完全重复的行(保留第一次出现的记录)
# ~ 是取反运算符
df = df[~df.duplicated()]

查找重复值:

  • 使用 df.duplicated() 识别重复行;它会返回一个布尔值 Series。
  • 使用 ~df.duplicated() 可以只保留非重复行。
  • 可以通过 subset 指定列名列表,只根据这些列判断是否重复。
  • 使用 keep=False 可以标记所有重复项。

通过指定列子集,可以找出同一个用户在同一天发布多条内容的记录。

python
# 根据 'user' 和 'date' 列查找重复行(保留所有重复记录)
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

4重新排序和重塑数据

使用 sort_values() 按多个列对行排序。

python
# 先按 'retweet_count',再按 'user.followers_count' 降序排序
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

重新排序和重塑:

  • 使用 df.sort_values(by=['col1', 'col2'], ascending=False) 可以按多个列进行降序排序。
  • 使用 df.transpose() 可以交换行和列。

当需要切换行和列以便检查数据时,可以转置 DataFrame。

python
df.transpose().head(3) # 查看行列互换后的 DataFrame
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

5连接数据

读取第二个数据集,并使用 concat() 合并。

python
path2 = "../../../src/data/keto-and-vegan.csv"
df2 = pd.read_csv(path2, encoding="latin-1") # 加载 df
df2.head(2) # 查看前 2 行
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

将列结构匹配的数据表纵向追加:

python
# 纵向拼接 df 和 df2(堆叠行)
pd.concat([df, df2]).iloc[428:432,] # 查看第 428 到 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...

连接数据:

  • 使用 pd.read_csv() 读取额外数据集,必要时指定 encoding。
  • 使用 pd.concat([df1, df2]) 可以将列结构匹配的 DataFrame 纵向拼接。
  • 使用 .reset_index(drop=True) 可以重置索引,使合并后的行索引连续。

拼接后,如果希望得到连续的行索引,可以重置索引。

python
# 拼接 df 和 df2,然后重置索引
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...

6分组和聚合

使用 groupby() 搭配 agg() 可以按组计算汇总统计值。下面的例子会计算每个用户的总转发量和平均粉丝数。

python
# 按 'user' 分组,然后对 'retweet_count' 求和,
# 对 'user.followers_count' 求平均值
df_agg = df.groupby("user").agg(
    {"retweet_count": "sum", "user.followers_count": "mean",}
)

# 查看聚合结果
df_agg.head(3)
retweet_countuser.followers_count
user
1nnkeeper0557.0
353a9f40f97e4a924440.0
6M70_JET0548.0

分组和聚合:

  • 使用 df.groupby('column').agg({'col1': 'sum', 'col2': 'mean'}) 可以按某一列分组,并计算聚合统计值。
  • 可以使用 df[~df.duplicated(subset='column')].shape 或 df['column'].nunique() 检查分组数量。

可以将分组结果与唯一用户数量进行比较:

python
# 通过基于 'user' 列删除重复值来统计唯一用户
df[~df.duplicated(subset="user")].shape
(390, 16)
python
# 或者直接用 nunique() 统计唯一用户数量
df["user"].nunique()
390

7Melt 和 Pivot

7.1Melt 数据

Melt: wide → long

使用 melt() 可以将宽表转换为长表,便于分析和绘图。

python
# 创建一个包含宠物类型和数量的宽格式示例 DataFrame
df_wide = pd.DataFrame(
    data=[
        ["cat", 4, 5],
        ["dog", 7, 4],
        ["rabbit", 2, 3],
    ],
    columns=["pet", "male", "female"],
)

df_wide # 查看该 DataFrame
petmalefemale
0cat45
1dog74
2rabbit23

不传入参数时,melt() 会将所有列折叠为 variable-value 形式。

python
df_wide.melt() # 将所有列转换为变量-值对(转换为长表)
variablevalue
0petcat
1petdog
2petrabbit
3male4
4male7
5male2
6female5
7female4
8female3

可以指定标识符列和值列,得到结构更清晰的长表。

python
melted_df = pd.melt(
    df_wide,
    id_vars=["pet"], # 保留 'pet' 作为标识符列
    value_vars=["male", "female"], # 值列
    var_name="sex", # 新变量列的名称
    value_name="count", # 新值列的名称
)

7.2Pivot 数据

Pivot: long → wide

将长表重新转换回宽表:

python
df_pivot = melted_df.pivot(
    index="pet", # 标识符列变为索引
    columns="sex", # 变量列中的类别变为新列
    values="count", # 值列变为新的数值
).reset_index() # 重置索引,将 'pet' 转回普通列

df_pivot.columns.name = None # 移除列索引的名称

df_pivot # 查看透视后的 DataFrame
petfemalemale
0cat54
1dog47
2rabbit32

当 index/column 组合存在重复值时,应使用 pivot_table() 而不是 pivot(),并指定类似 aggfunc='mean' 的聚合函数来汇总重复项。

例如,如果存在重复的宠物记录:

python
# 创建一个包含重复宠物记录的示例 DataFrame
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 # 查看包含重复值的长格式 DataFrame
petsexcount
0catmale4
1catfemale5
2dogfemale7
3dogmale4
4rabbitmale2
5rabbitfemale3

要将这个长表转换回宽表,可以使用 pivot_table() 处理重复项:

python
# 创建透视表,对重复记录的数量取平均值
(df_long
.pivot_table(
    index="pet",
    columns="sex",
    values="count",
    aggfunc="mean", # 对重复记录的数量取平均值
)
.rename_axis(None, axis=1) # 移除列标题的名称
.rename_axis(None) # 移除索引的名称
)
femalemale
cat5.04.0
dog7.04.0
rabbit3.02.0

↑↓ 移动Enter 打开Esc 关闭 或 / 打开搜索