二、Pandas-5.轴向上删除条目

"""
    drop:在轴向上删除一个或更多的条目,返回一个含有指示值或轴向上删除值的新对象
"""
import numpy as np
import pandas as pd

obj = pd.Series(np.arange(5), index=["Zero", "One", "Two", "Three", "Four"])
print(obj)
"""
Zero     0
One      1
Two      2
Three    3
Four     4
dtype: int32
"""

obj = obj.drop("Zero")
print(obj)
"""
One      1
Two      2
Three    3
Four     4
dtype: int32
"""

# ▶知识点1:如果所删除的索引不存在,则会报错KeyError: "xxx not found in axis"
obj = obj.drop(["One", "Two"])
print(obj)
"""
Three    3
Four     4
dtype: int32
"""

df_1 = pd.DataFrame(np.arange(16).reshape((4, 4)), index=["XiaoMing", "XiaoYing", "XiaoHong", "XiaoGang"],
                    columns=["Chinese", "Math", "English", "History"])
print(df_1)
"""
          Chinese  Math  English  History
XiaoMing        0     1        2        3
XiaoYing        4     5        6        7
XiaoHong        8     9       10       11
XiaoGang       12    13       14       15
"""
# ▶知识点2:在DataFrame中,索引值可以从轴向上删除
# ▶知识点3:在DataFrame中,调用drop时,使用【标签序列】会根据【行标签】删除值(轴0,即axis=0)
df_1 = df_1.drop(["XiaoMing", "XiaoHong"])
print(df_1)
"""
          Chinese  Math  English  History
XiaoYing        4     5        6        7
XiaoGang       12    13       14       15
"""

# ▶知识点4:使用【axis=1】或【axis="columns"】会根据【列标签】删除值

df_1 = df_1.drop("English", axis="columns")
print(df_1)
"""
          Chinese  Math  History
XiaoYing        4     5        7
XiaoGang       12    13       15
"""

df_1 = df_1.drop(["Math", "History"], axis=1)
print(df_1)
"""
          Chinese
XiaoYing        4
XiaoGang       12
"""
# ▶知识点5:很多函数,例如drop,会修改Series或DataFrame的尺寸和形状,这些方法直接操作原对象而不返回新对象
df_1.drop("XiaoGang", inplace=True)  # ▶知识点6:inplace属性,会清除被删除的数据
print(df_1)
"""
          Chinese
XiaoYing        4
"""

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值