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
"""