目录
重新索引
Series
reindex方法
s = pd.Series([1, 3, 5, 6, 8], index=list('acefh'))
s
运行结果为:
a 1
c 3
e 5
f 6
h 8
# reindex(list类型)
s.reindex(list('abcdefgh'))
运行结果为:
a 1
b NaN
c 3
d NaN
e 5
f 6
g NaN
h 8
# fill_value参数
s.reindex(list('abcdefgh'), fill_value=0)
运行结果为:
a 1
b 0
c 3
d 0
e 5
f 6
g 0
h 8
# method参数
# method='bfill'
s.reindex(list('abcdefgh'), method='ffill')
a 1
b 1
c 3
d 3
e 5
f 6
g 6
h 8
DataFrame
reindex方法
使用方法和Series类型类似,格式为:
# 例如:
df.reindex(index=list('ABCDEFGH'))
df.reindex(columns=['one', 'three', 'five', 'seven'])
- fill_value参数的用法相同;
- method参数(ffill、bfill)只对行reindex时有效。
丢弃部分数据
drop方法
格式为:
df = pd.DataFrame(np.random.randn(4, 6), index=list('ABCD'), columns=['one', 'two', 'three', 'four', 'five', 'six'])
# 例如:
df.drop('A')
# 丢弃整列数据时要指定对列操作
df2 = df.drop(['two', 'four'], axis=1)
函数应用
- apply: 将数据按行或列进行计算
- applymap: 将数据按元素为进行计算
apply方法
df = pd.DataFrame(np.arange(12).reshape(4, 3), index=['one', 'two', 'three', 'four'], columns=list('ABC'))
df
# 每一列作为一个 Series 作为参数传递给 lambda 函数
df.apply(lambda x: x.max() - x.min())
运行结果为:
A 9
B 9
C 9
# 每一行作为一个 Series 作为参数传递给 lambda 函数
df.apply(lambda x: x.max() - x.min(), axis=1)
运行结果为:
one 2
two 2
three 2
four 2
# 返回多个值组成的 Series
def min_max(x):
return pd.Series([x.min(), x.max()], index=['min', 'max'])
df.apply(min_max, axis=1)
applymap方法
df = pd.DataFrame(np.random.randn(4, 3), index=['one', 'two', 'three', 'four'], columns=list('ABC'))
df
formater = '{0:.02f}'.format
# formater = lambda x: '%.02f' % x
df.applymap(formater)
排序和排名
Series
rank方法
# rank方法得到每一个数排名后的名次
s = pd.Series([3, 6, 2, 6, 4])
s.rank()
运行结果为:
0 2.0
1 4.5
2 1.0
3 4.5
4 3.0
# method=‘first’:第一个出现的排序更前
# ascending决定正序还是倒序
s.rank(method='first', ascending=False)
运行结果为:
0 4
1 1
2 5
3 2
4 3
DataFrame
sort_value方法
df = pd.DataFrame(np.random.randint(1, 10, (4, 3)), index=list('ABCD'), columns=['one', 'two', 'three'])
df
# by参数决定根据某一列中值的大小来排序所有行
# 默认对行进行排序
df.sort_values(by='one')
数据唯一性及成员资格
适用于Series
数据唯一性
s = pd.Series(list('abbcdabacad'))
s
运行结果为:
0 a
1 b
2 b
3 c
4 d
5 a
6 b
7 a
8 c
9 a
10 d
unique函数
# 得到Series中不重复的所有元素
s.unique()
运行结果为:
array(['a', 'b', 'c', 'd'], dtype=object)
value_counts函数
# 统计不重复元素的出现次数
a 4
b 3
d 2
c 2
成员资格
isin函数
参数为一个list,输出Series中的所有参数是否存在于给定的list中。
s.isin(['a', 'b', 'c'])
运行结果为:
0 True
1 True
2 True
3 True
4 False
5 True
6 True
7 True
8 True
9 True
10 False
Series的重复元素索引
DataFrame的索引在pandas核心数据结构中提到过。
s = pd.Series(np.arange(6), index=list('abcbda'))
s
运行结果为:
a 0
b 1
c 2
b 3
d 4
a 5
s['a']
运行结果为:
a 0
a 5
s['c']
运行结果为:
2
s.index.is_unique
# 判断索引是否有重复
运行结果为:
False
s.index.unique()
# 输出不重复的索引元素
运行结果为:
array(['a', 'b', 'c', 'd'], dtype=object)
s.groupby(s.index).sum()
# 分组运算(根据索引分组)
运行结果为:
a 5
b 4
c 2
d 4
层次化索引
可以使数据在一个轴上有多个索引级别。即可以用二维的数据表达更高维度的数据,使数据组织方式更清晰。它使用 pd.MultiIndex 类来表示。
层次化索引的作用:比如我们在分析股票数据,我们的一级行索引可以是日期;二级行索引可以是股票代码,列索引可以是股票的交易量,开盘价,收盘价等等。这样我们就可以把多个股票放在同一个时间维度下进行考察和分析。
Series多层索引
# 建立多层索引
a = [['a', 'a', 'a', 'b', 'b', 'c', 'c'], [1, 2, 3, 1, 2, 2, 3]]
tuples = list(zip(*a))
tuples
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
index
运行结果为:
[('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 2), ('c', 3)]
MultiIndex(levels=[[u'a', u'b', u'c'], [1, 2, 3]],
labels=[[0, 0, 0, 1, 1, 2, 2], [0, 1, 2, 0, 1, 1, 2]],
names=[u'first', u'second'])
# 将多层索引引入Series
s = pd.Series(np.random.randn(7), index=index)
s
运行结果为:
first second
a 1 -1.192113
2 0.226627
3 0.390052
b 1 0.045297
2 1.552926
c 2 0.014007
3 -0.257103
s[]中的第一个参数值为第一层索引
s['b']
运行结果为:
second
1 0.045297
2 1.552926
s['b':'c']
运行结果为:
first second
b 1 0.045297
2 1.552926
c 2 0.014007
3 -0.257103
s[]中的第二个参数值为第二层索引,以此类推
s[['b', 'a']]
运行结果为:
first second
b 1 0.045297
2 1.552926
a 1 -1.192113
2 0.226627
3 0.390052
s['b', 1]
运行结果为:
0.045297227336673768
只根据第二层索引来引用数据要用[:,index]的格式
s[:, 2]
运行结果为:
first
a 0.226627
b 1.552926
c 0.014007
DataFrame多层索引
df = pd.DataFrame(np.random.randint(1, 10, (4, 3)),
index=[['a', 'a', 'b', 'b'], [1, 2, 1, 2]],
columns=[['one', 'one', 'two'], ['blue', 'red', 'blue']])
df.index.names = ['row-1', 'row-2']
df.columns.names = ['col-1', 'col-2']
df
df.loc['a']
col-1 col-2
one blue 7
red 6
two blue 7
运行结果为:
col-1 col-2
one blue 7
red 6
two blue 7
索引交换及排序
df
df2 = df.swaplevel('row-1', 'row-2')
df2
df2.sortlevel(0)
按照索引级别进行统计
df
# 根据一级索引进行求和操作
df.sum(level=0)
# 根据二级索引进行求和操作
df.sum(level=1)
索引与列的转换
df = pd.DataFrame({
'a': range(7),
'b': range(7, 0, -1),
'c': ['one', 'one', 'one', 'two', 'two', 'two', 'two'],
'd': [0, 1, 2, 0, 1, 2, 3]
})
df
df.set_index('c')
df2 = df.set_index(['c', 'd'])
df2
df3 = df2.reset_index().sort_index('columns')
df3