reindex基本用法
obj = Series([4.5, 7.2, -5.3, 3.6], index=['d', 'b', 'a', 'c'])
>> obj
d 4.5
b 7.2
a -5.3
c 3.6
obj2 = obj.reindex(['a', 'b', 'c', 'd', 'e'], fill_value=0)
>> obj2
a -5.3
b 7.2
c 3.6
d 4.5
e 0.0
obj3 = Series(['blue', 'purple', 'yellow'], index=[0, 2, 4])
obj3.reindex(range(6), method='ffill')
>> obj3
0 bule
1 bule
2 purple
3 purple
4 yellow
5 yellow
reindex修改索引(行)、列、或同时修改
frame = DataFrame(np.arange(9).reshape((3, 3)), index=['a', 'c', 'd'],
columns=['Ohio','Texas','California'])
>> frame
Ohio Texas California
a 0 1 2
c 3 4 5
d 6 7 8
# 仅传入一个序列,会重新索引行
frame2 = frame.reindex(['a', 'b', 'c', 'd'])
>> frame2
Ohio Texas California
a 0 1 2
b NaN NaN NaN
c 3 4 5
d 6 7 8
# 使用columns关键字,重新索引列
states = ['Texas', 'Utha', 'California']
frame3 = frame.reindex(columns=states)
>> frame3
Texas Utha California
a 1 NaN 2
c 4 NaN 5
d 7 NaN 8
# 同时对行列重新索引,但插值只能按行应用(轴0)
frame4 = frame.reindex(index=['a', 'b', 'c', 'd'], method='ffill', columns=states)
>> frame4
Texas Utha California
a 1 NaN 2
b 1 NaN 2
c 4 NaN 5
d 7 NaN 8
# ix的标签索引功能
>> frame.ix[['a', 'b', 'c', 'd'],states]
Texas Utha California
a 1 NaN 2
b NaN NaN NaN
c 4 NaN 5
d 7 NaN 8
reindex函数的参数
参数 | 说明 |
---|---|
index | 用作索引的新序列 |
method | fill,pad前向填充。bfill,backfill后向填充 |
fill_value | 缺失值的替代值 |
limit | 前向或后向填充的最大填充量 |
level | 在multiIndex的指定级别上匹配简单索引,否则选取其子集 |
copy | 默认为True |
# 删除任意轴上索引,axis指定轴
data = DataFrame(np.arange(16).reshape((4, 4)),
index=['Ohio', 'Colorado', 'Utha', 'New York'],
columns=['one', 'two', 'three', 'four'])
>> data.drop(['Colorado', 'Ohio'])
one two three four
Utah 8 9 10 11
New York 12 13 14 15
>> data.drop(['two', 'four'], axis=1)
one three
Ohio 0 2
Colorado 4 6
Utah 8 10
New York 12 14
data = DataFrame(np.range(16).reshape((4, 4)),
index=['Ohio', 'Colorado', 'Utah', 'New York'],
columns=['one', 'two', 'three', 'four'])
>> data
one two three four
Ohio 0 1 2 3
Colorado 4 5 6 7
Utah 8 9 10 11
New York 12 13 14 15
# obj[val]
>> data[['three', 'one']]
three one
Ohio 2 0
Colorado 6 4
Utah 10 8
New York 14 12
>> data[:2]
one two three four
Ohio 0 1 2 3
Colorado 4 5 6 7
>> data[data['three'] > 5]
one two three four
Colorado 4 5 6 7
Utah 8 9 10 11
New York 12 13 14 15
# obj.ix[val]
>> data.ix['Colorado', ['two', 'three']]
two 5
three 6
Name: Colorado
>> data.ix[['Colorado', 'Utah'], [3, 0, 1]]
four one two
Colorado 7 4 5
Utah 11 8 9
>> data.ix[2]
one 8
two 9
three 10
four 11
Name: Utah
DataFrame的索引选项
类型 | 说明 |
---|---|
obj[val] | 选取DataFramed的单个列或一组列。在一些特殊情况下比较便利:布尔型数组(过滤行)、切片(行切片)、布尔型DataFrame(根据条件设置值) |
obj.ix[val] | 选取单个行或一组行 |
obj.ix[:,val] | 选取单个列或列子集 |
obj.ix[val1,val2] | 同时选取行和列 |
reindex | 将一个或多个轴匹配到新索引 |
xs | 根据标签选取单行或单列,并返回一个Series |
icol, irow | 根据整数位置选取单列或单行,并返回一个Series |
get_value, set_value | 根据行标签和列标签选取单个值 |
pandas一个重要功能是,可以对不同索引的对象进行算术运算,对象相加时如果存在不同的索引对,则结果的索引就是该索引对的并集
df1 = DafaFrame(np.arange(9).reshape((3, 3)),
columns=list('bcd'),
index=['Ohio','Texas','Colorado'])
df2 = DafaFrame(np.arange(12).reshape((4, 3)),
columns=list('bde'),
index=['Utah', 'Ohio','Texas','Colorado'])
>> df1
b c d
Ohio 0 1 2
Texas 3 4 5
Colorado 6 7 8
>> df2
b d e
Utah 0 1 2
Ohio 3 4 5
Texas 6 7 8
Oregon 9 10 11
>> df1 + df2
b c d e
Colorado NaN NaN NaN NaN
Ohio 3 NaN 6 NaN
Oregon NaN NaN NaN NaN
Texas 9 NaN 12 NaN
Utah NaN NaN NaN NaN
>> df1.add(df2,fill_value=0)
b c d e
Colorado 6 7 8 0
Ohio 3 1 6 5
Oregon 9 0 10 11
Texas 9 4 12 8
Utah 0 0 1 2
方法 | 说明 |
---|---|
add | 加法运算 |
sub | 减法运算 |
div | 除法运算 |
mul | 乘法运算 |
Numpy的ufuns(元素级数组方法)也可用于操作pandas对象
# 求绝对值
>> np.abs(df1)
b c d
Ohio 0 1 2
Texas 3 4 5
Colorado 6 7 8
# apply方法
f = lambda x: x.max() - x.min()
>> df1.apply(f)
b 6
c 6
d 6
>> df1.apply(f, axis=1)
Ohio 2
Texas 2
Colorado 2
# 传递给apply的函数可以返回由多个值组成的series
def f(x):
return Series([x.min(), x.max()], index=['min', 'max'])
>> df1.apply(f):
b c d
min 0 1 2
max 6 7 8
# applymap方法
# 得到dataframe中各个浮点值的格式化字符串
format = lambda x: '%.2f' % x
frame.applymap(format)
frame = DataFrame(np.arange(8).reshape((2, 4)), index=['two', 'one'],
columns=['d', 'a', 'b', 'c'])
# 默认对行index排序
>> frame.sort_index()
d a b c
one 4 5 6 7
two 0 1 2 3
# 设置axis对columns排序
>> frame.sort_index(axis=1)
a b c d
two 1 2 3 0
one 5 6 7 4
# 默认升序排序,设置降序
frame.sort_index(axis=1, ascending=False)
# 根据一个或多个列的中的值进行排序
frame.sort_index(by='b')
d a b c
two 0 1 2 3
one 4 5 6 7
obj = Series([7, -5, 7, 4, 2, 0, 4])
>> obj.rank()
0 6.5
1 1.0
2 6.5
3 4.5
4 3.0
5 2.0
6 4.5
>> obj.rank(method='first')
0 6
1 1
2 7
3 4
4 3
5 2
6 5
# 降序排
obj.rank(ascending=False, method='max')
# 在列计算排名
obj.rank(axis=1)
排名时用于破坏平级关系的method选项
method | 说明 |
---|---|
average | 默认,相等分组中为各值平均排名 |
min | 使用整个分组的最小排名 |
max | 使用整个分组的最大排名 |
first | 按值在原始数据中的出现顺序分配排名 |
>> df
one two
a 1.4 NaN
b 7.1 -4.5
c NaN NaN
d 0.75 -1.3
# 按列求和
>> df.sum()
one 9.25
two -5.8
# 按行求和
>> df.sum(axis=1)
a 1.4
b 2.6
c NaN
d -0.55
# Na值会被自动排除,除非整个切片都是Na,skipna选项可以禁用该功能
>> df.mean(axis=1, skipna=False)
a NaN
b 1.300
c NaN
d -0.275
约简方法的选项
选项 | 说明 |
---|---|
axis | 轴,行用0,列用1 |
skipna | 排除缺失值,默认为True |
level | 如果轴式层次化索引的(MultiIndex),则根据level分组 |
# 达到最小值或最大值的索引
>> df.idxmax()
one b
two a
# 累计型
>> df.cumsum()
one two
a 1.4 NaN
b 8.5 -4.5
c NaN NaN
d 9.25 -5.8
# describe
>> df.describe()
one two
count 3.000000 2.000000
mean 3.083333 -2.900000
std 3.493685 2.262742
min 0.750000 -4.500000
max 7.100000 -1.300000
描述和汇总统计
方法 | 说明 |
---|---|
count | 非NA值的数量 |
describe | 针对series或各DataFrame列计算汇总统计 |
min、max | 最大最小值 |
argmin、argmax | 能够获取到最小最大值的索引位置 |
idxmin、idxmax | 能够获取到最小最大值的索引值 |
quantile | 计算样本的分位数(0到1) |
sum | 总和 |
mean | 平均值 |
median | 算术中位数 |
mad | 根据平均值计算平均绝对离差 |
var | 样本值的方差 |
std | 样本值的标准差 |
skew | 样本值的偏度(三阶矩) |
kurt | 样本值的峰度(四阶) |
cumsum | 累计和 |
cummin、cummax | 累计最大值和累计最小值 |
cumprod | 累计积 |
diff | 计算一阶差分(对时间序列很有用) |
pct_change | 计算百分数变化 |
obj = Series(['c', 'a', 'd', 'a', 'a', 'b', 'b', 'c', 'c'])
# 唯一值
>> obj.unique()
array([c, a, d, b], dtype=object)
# 值计数
>> obj.value_counts()
c 3
a 3
b 2
d 1
# 判断矢量化集合的成员资格
>> obj.isin(['b', 'c'])
0 True
1 False
2 False
3 False
4 False
5 True
6 True
7 True
8 True
from numpy import nan as NA
data = DataFrame([[1, 6.5, 3], [1, NA, NA],
[NA, NA, NA],[NA, 6.5, 3]])
cleaned = data.dropna()
>> data
0 1 2
0 1 6.5 3
1 1 NaN NaN
2 NaN NaN NaN
3 NaN 6.5 3
>> cleand
0 1 2
0 1 6.5 3
# how=all 丢弃全为Na的行
>> data.dropna(how='all')
0 1 2
0 1 6.5 3
1 1 NaN NaN
3 NaN 6.5 3
# thresh
>> data.dropna(thresh=3) # 一行中有3个值非空,就保留
0 1 2
0 1 6.5 3
# fillna
>> data.fillna(0)
0 1 2
0 1 6.5 3
1 1 0 0
2 0 0 0
3 0 6.5 3
# 对不同列填充不同值
>> data.fillna({1: 0.5, 2: -1})
0 1 2
0 1 6.5 3
1 1 0.5 -1
2 NaN 0.5 -1
3 NaN 6.5 3
# method='ffill'
>> data.fillna(method='ffill', limit=2)
0 1 2
0 1 6.5 3
1 1 6.5 3
2 1 6.5 3
3 1 6.5 3
>> data.fillna(data.mean())
fillna函数的参数
参数 | 说明 |
---|---|
value | 用于填充缺失值的标量值或字典对象 |
method | 插值方式,默认ffill |
axis | 待填充的轴,默认axis=0 |
inplace | 修改调用者对象而不产生副本 |
limit | 对于前向或后向填充,可以连续填充的最大数量 |
data = Series(np.random.randn(10),
index=[['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd'],
[1, 2, 3, 1, 2, 3, 1, 2, 2, 3]])
>> data
a 1 0.670216
2 0.852965
3 -0.955869
b 1 -0.023493
2 -2.304234
3 -0.652469
c 1 -1.218302
2 -1.332610
d 2 1.074623
3 0.723642
>> data['b']
1 -0.023493
2 -2.304234
3 -0.652469
>> data.ix[['b', 'd']]
b 1 -0.023493
2 -2.304234
3 -0.652469
d 2 1.074623
3 0.723642
# 在内层选取
>> data[:, 2]
a 0.852965
b -2.304234
c -1.332610
d 1.074623
>> data.unstack()
1 2 3
a 0.670216 0.852965 -0.955869
b -0.023493 -2.304234 -0.652469
c -1.218302 -1.332610 NaN
d NaN 1.074623 0.723642
>> data.unstack().stack()
a 1 0.670216
2 0.852965
3 -0.955869
b 1 -0.023493
2 -2.304234
3 -0.652469
c 1 -1.218302
2 -1.332610
d 2 1.074623
3 0.723642
有时需要重新调整某条轴上各级别的顺序,或根据指定级别上的值对数据进行排序。
swaplevel接受两个级别编号或名称,并返回一个互换了级别的新对象。
frame = DataFrame(np.arange(12).reshape((4, 3)),
index=[['a', 'a', 'b', 'b'], [1, 2, 1, 2]],
columns=[['Ohio', 'Ohio', 'Colorado'],
['Green', 'Red', 'Green']])
frame.index.names = ['key1', 'key2']
frame.columns.names = ['state', 'color']
>> frame
state Ohio Colorado
color Green Red Green
key1 key2
a 1 0 1 2
2 3 4 5
b 1 6 7 8
2 9 10 11
>> frame.swaplevel('key1', 'key2')
state Ohio Colorado
color Green Red Green
key2 key1
1 a 0 1 2
2 a 3 4 5
1 b 6 7 8
2 b 9 10 11
# sortlevel根据单个级别中的值对数据排序
>> frame.sortlevel(1)
state Ohio Colorado
color Green Red Green
key1 key2
a 1 0 1 2
b 1 6 7 8
a 2 3 4 5
b 2 9 10 11
>> frame.swaplevel(0, 1).sortlevel(0)
state Ohio Colorado
color Green Red Green
key2 key1
1 a 0 1 2
b 6 7 8
2 a 3 4 5
b 9 10 11
>> frame.sum(level='key2')
state Ohio Colorado
color Green Red Green
key2
1 6 8 10
2 12 14 16
>> frame.sum(level='color', axis=1)
color Green Red
key1 key2
a 1 2 1
2 8 4
b 1 14 7
2 20 10