pandas 有两个核心对象: DataFrame(数据框) 和 Series(序列).
- DataFrame 是 一张表table , matrix
- Series是一列数据, vector
- 一个DataFrame 也就是很多个Series拼起来,每一个列就是一个Series
导入:
创建Dataframe
参数是一个字典也就是key是列 value是行
pd.DataFrame({'Yes': [50, 21], 'No': [131, 2]})
|
index 也就是行的索引 默认是 0,1,2...
创建Series(序列)
参数是 list
pd.Series([1, 2, 3, 4, 5])
|
也有index 没有列 但是有一个总的name.
pd.Series([30, 35, 40], index=['2015 Sales', '2016 Sales', '2017 Sales'], name='Product A')
|
读取数据
读取csv(Comma-seperated values)
使用 pd.read_csv() 参数是地址
wine_reviews = pd.read_csv("../input/wine-reviews/winemag-data-130k-v2.csv")
|
有一个属性 .shape 和一个方法 .head()
wine_reviews.shape wine_reviews.head()
|
如果本身文件有index的列 那就可以使用 index_col指定第0列来做index
pd.read_csv('./winemag-data-130k-v2.csv', index_col=0)
|
写出数据
Indexing, Selecting & Assigning
Native accessors,原生取值方式
python的取值 列名 然后row
reviews.country reviews['country'] reviews['country'][0]
|
(index-based selection)
- iloc integer
- loc name
- 先行后列
操控索引
reviews.set_index("title")
|
可以把某一行转换城Index 跟index_col的不同 其实就是 iloc和 loc的不同一个是integer 一个是text
Conditional selection
先写一个条件
reviews.country == 'Italy'
|
然后会生成一个series也就是 有True和false的Series
这种series 叫 Booleea mask
只留下True的行
reviews.loc[reviews.country == 'Italy'] reviews.loc[(reviews.country == 'Italy') & (reviews.points >= 90)] reviews.loc[(reviews.country == 'Italy') | (reviews.points >= 90)]
|
built-in conditional selectors,内置build in 的
reviews.loc[reviews.country.isin(['Italy', 'France'])] reviews.loc[reviews.price.notnull()] reviews.loc[reviews.price.isnull()]
|
Assigning data 赋值
reviews['critic'] = 'everyone' reviews['index_backwards'] = range(len(reviews), 0, -1)
|
汇总函数(Summary Functions)
把很多个值压缩成一个值 类似SQL的average那些functions
Maps
把数据转换成更有用的形式
方法1 使用map函数:
review_points_mean = reviews.points.mean() reviews.points.map(lambda p: p - review_points_mean)
|
方式2 使用apply:
def remean_points(row): row.points = row.points - review_points_mean return row
reviews.apply(remean_points, axis='columns')
|
注意: map 和 apply 不会修改原Dataframe 这是一个新的result 需要拿变量保存
SQL里面的groupby 和 order by
每个分数有多少条评论
reviews.groupby('points').points.count()
|
跟 value_counts 相同
agg()(聚合, aggregate)
reviews.groupby(['country']).price.agg([len, min, max])
|
MultiIndex
- 按一列分组,结果的索引只有一层。
- 按两列分组,结果的索引就有两层。
r = df.groupby(['country', 'province']).price.agg(['count', 'max'])
|
rename():改列名或索引值
reviews.rename(columns={'points': 'score'}) reviews.rename(index={0: 'firstEntry', 1: 'secondEntry'})
|
reviews.rename_axis("wines", axis='rows').rename_axis("fields", axis='columns')
|
一个 DataFrame(数据框)有两个轴(axis,轴):
- 行轴(rows axis,行轴):左边那一列编号,也叫行索引(index,索引)。
- 列轴(columns axis,列轴):顶部那一行列名(columns,列标签)。
每个轴本身可以有一个名字(name,名称)。默认情况下,这个名字是 None(空)。rename_axis() 的作用就是给这两个轴起名字。
最主要就是可读性显示的时候会显示行是什么 列是什么
合并

left = canadian_youtube.set_index(['title', 'trending_date']) right = british_youtube.set_index(['title', 'trending_date']) left.join(right, lsuffix='_CAN', rsuffix='_UK')
|
两个表的列名相同,会发生冲突。lsuffix 和 rsuffix 给左表和右表的列加后缀(suffix,后缀),例如 views_CAN 和 views_UK。