DataFrame对象操作
重新索引
.reindex()能够改变或重排Series和DataFrame索引
.reindex(index=None, columns=None,…)的参数
参数说明index, columns新的行列自定义索引fill_value重新索引中,用于填充缺失位置的值method填充方法, ffill当前值向前填充,bfill向后填充limit最大大填充量copy默认True,生成新的对象,False时,新旧相等不复制 索引类型Series和DataFrame的索引是Index类型 Index对象是不可修改类型
索引类型常用方法
方法说明.append(idx)连接另一个Index对象,产生新的Index对象.diff(idx)计算差集,产生新的Index对象.intersection(idx)计算交集.union(idx)计算并集.delete(loc)删除loc位置处的元素.insert(loc,e)在loc位置增加一个元素e.drop()能够删除Series和DataFrame指定行或列索引
代码示例# -*- coding: utf-8 -*-
# @File : dataframe_demo2.py
# @Date : 2018-05-20
# DataFrame对象操作
from pandas import DataFrame
dt = {
"城市": ["北京", "上海", "南京", "天津"],
"人口": [200, 20, 30, 40],
"收入": [10, 20, 40, 50]
}
df = DataFrame(dt, index=["c1", "c2", "c3", "c4"])
print(df)
"""
城市 人口 收入
c1 北京 200 10
c2 上海 20 20
c3 南京 30 40
c4 天津 40 50
"""
# 重新索引行,排序
df2 = df.reindex(index=["c4", "c3", "c2", "c1"])
print(df2)
"""
城市 人口 收入
c4 天津 40 50
c3 南京 30 40
c2 上海 20 20
c1 北京 200 10
"""
# 重新索引列,排序
df3 = df.reindex(columns=["城市", "收入", "人口"])
print(df3)
"""
城市 收入 人口
c1 北京 10 200
c2 上海 20 20
c3 南京 40 30
c4 天津 50 40
"""
# 插入列索引
col = df.columns.insert(3, "新增")
print(col)
"""
Index(['城市', '人口', '收入', '新增'], dtype='object')
"""
# 增加数据,默认填充200
df4 = df.reindex(columns=col, fill_value=200)
print(df4)
"""
城市 人口 收入 新增
c1 北京 200 10 200
c2 上海 20 20 200
c3 南京 30 40 200
c4 天津 40 50 200
"""
# 删除插入索引
nc = df.columns.delete(2)
ni = df.index.insert(5, "c0")
df5 = df.reindex(index=ni, columns=nc)
print(df5)
"""
城市 人口
c1 北京 200.0
c2 上海 20.0
c3 南京 30.0
c4 天津 40.0
c0 NaN NaN
"""
# DataFrame删除行
df6 = df5.drop("c1")
print(df6)
"""
城市 人口
c2 上海 20.0
c3 南京 30.0
c4 天津 40.0
c0 NaN NaN
"""
# DataFrame删除列
df7 = df6.drop("人口", axis=1)
print(df7)
"""
城市
c2 上海
c3 南京
c4 天津
c0 NaN
"""