您的位置:首页 > 编程语言 > Python开发

python-pandas的基本用法03

2017-08-05 20:06 701 查看

pandas的基本用法03-reindex()

# -*- coding: utf-8 -*-
import numpy as np
from pandas import DataFrame, Series
from matplotlib.pyplot import axis

s = Series([1,2,3,4], index=['a','b','c','d'])
s2 = s.reindex(['a','b','c','d','e'], fill_value=0)
print s2
# a    1
# b    2
# c    3
# d    4
# e    0
# dtype: int64
s2 = s.reindex(['a','b','c','d','e'], method='ffill')
print s2
# a    1
# b    2
# c    3
# d    4
# e    4
# dtype: int64

print '对DataFrame重新指定索引'
f = DataFrame(np.arange(9).reshape(3, 3),
index = ['i1', 'i2', 'i3'],
columns = ['c1','c2','c3'])
print f
#     c1  c2  c3
# i1   0   1   2
# i2   3   4   5
# i3   6   7   8

f2 = f.reindex(['a','b','c', 'd'])
print f2
#  c1  c2  c3
# a NaN NaN NaN
# b NaN NaN NaN
# c NaN NaN NaN
# d NaN NaN NaN

print '重新指定column'
names = ['c1', 'c2', 'Tony']
print f.reindex(columns=names)
#     c1  c2  Tony
# i1   0   1   NaN
# i2   3   4   NaN
# i3   6   7   NaN

print '对DataFrame重新指定索引并指定填元素充方法'
print f
#     c1  c2  c3
# i1   0   1   2
# i2   3   4   5
# i3   6   7   8
f2 = f.reindex(index=['i1', 'i2', 'x'],
method='ffill', columns=names)
print f2
#     c1  c2  Tony
# i1   0   1   NaN
# i2   3   4   NaN
# x    6   7   NaN
print f2.fillna(method='ffill', axis=1)
#     c1  c2  Tony
# i1   0   1     1
# i2   3   4     4
# x    6   7     7


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  pandas