Pandas数据处理技巧全解析
主要章节与要点
UFO 报告数据(
uforeports.csv)- 读取:
ufo = pd.read_csv('uforeports.csv') - 统计并查看类别分布:
ufo['Shape Reported'].value_counts(dropna=False)(包括缺失值) - 填充缺失值:
ufo['Shape Reported'].fillna(value='VARIOUS', inplace=True)将缺失值用VARIOUS替换 - 常见行/列选择:使用
loc选择指定行/列(例如ufo.loc[[0,1,2], :]、ufo.loc[:, ['Colors Reported','Shape Reported','State']]) - 条件过滤:
ufo[ufo.City == 'Oakland']或ufo.loc[ufo.City == 'Oakland','State'] - 用例演示:删除列(
.drop())、查看尾部数据(.head()/.tail()等)
- 读取:
pandas 索引(Index)及
drinksbycountry.csv- 读取:
drinks = pd.read_csv('drinksbycountry.csv') - 查看索引与列:
drinks.index、drinks.columns、drinks.shape - 将列设为索引:
drinks.set_index('country', inplace=True),随后可用drinks.loc['Brazil','beer_servings']用国家名访问行。 - 重置索引并恢复默认整数索引:
drinks.reset_index(inplace=True) - 修改索引名称:
drinks.index.name = 'country'或drinks.index.name = None - 按索引或列进行统计:
drinks.describe()和对统计结果的定位(例如drinks.describe().loc['25%','beer_servings'])
- 读取:
选择多行多列与位置索引
loc用法:基于标签选择行列(可用行标签切片、列表或布尔掩码)。iloc用法:基于整数位置选择(例如ufo.iloc[:,0:4])。- 列范围切片:
ufo.loc[:, 'Colors Reported':'Time'](使用列名范围切片)
其它实用示例
- 读取无表头、使用自定义分隔符的文件:
pd.read_table('movieusers.csv', header=None, sep='|') - 统计并排序:
drinks.continent.value_counts().sort_index()
- 读取无表头、使用自定义分隔符的文件:
关键代码片段(摘录并简短说明)
- 填充缺失值并统计:
ufo['Shape Reported'].value_counts(dropna=False)ufo['Shape Reported'].fillna(value='VARIOUS',inplace=True)ufo['Shape Reported'].value_counts()说明:先查看包含 NaN 的统计,再用fillna填充,最后确认填充结果。
- 索引设置与定位:
drinks=pd.read_csv('drinksbycountry.csv')drinks.set_index('country',inplace=True)drinks.loc['Brazil','beer_servings']说明:把country设置为索引后,可直接用国家名定位对应行的数据。
loc/iloc示例:
# 基于标签选择:ufo.loc[[0,1,2],:]# 基于位置选择:ufo.iloc[:,0:4]# 选择列范围:ufo.loc[:,'Colors Reported':'Time']- 描述性统计定位:
drinks.describe().loc['25%','beer_servings']