"""
目前为止所见过的示例中,轴索引都是唯一的(索引值),尽管pandas函数(比如reindex)需要标签是唯一的,但这个并不是强制性的
"""
import numpy as np
import pandas as pd
obj = pd.Series(range(5), index=["A", "A", "B", "C", "C"])
print(obj)
# ▶知识点1:is_unique可以判断标签是否唯一
print(obj.index.is_unique) # False
# 带有重复索引的情况下,数据选择是与之前操作有差别的主要情况。
# 根据一个标签索引多个条目会返回一个序列,而单个条目会返回标量值
print(obj.loc["A"])
"""
A 0
A 1
dtype: int64
"""
print(obj.loc["B"]) # 2
# 相同的逻辑可以拓展到DataFrame中进行行索引或者列索引
df_1 = pd.DataFrame(np.arange(20).reshape((5, 4)), index=["A", "A", "B", "C", "B"],
columns=["XiaoMing", "XiaoYing", "XiaoKe", "XiaoYing"])
print(df_1)
print(df_1.loc["A"])
"""
XiaoMing XiaoYing XiaoKe XiaoYing
A 0 1 2 3
A 4 5 6 7
"""
print(df_1.loc[["A", "B"]])
"""
XiaoMing XiaoYing XiaoKe XiaoYing
A 0 1 2 3
A 4 5 6 7
B 8 9 10 11
B 16 17 18 19
"""
print(df_1.XiaoYing)
"""
XiaoYing XiaoYing
A 1 3
A 5 7
B 9 11
C 13 15
B 17 19
"""
二、Pandas-12.含有重复标签的轴索引
最新推荐文章于 2022-09-09 17:20:28 发布