本文目录导读:

我来给你详细介绍Python Pandas中数据索引交叉的几种常用方法。
基础索引交叉示例
准备数据
import pandas as pd
import numpy as np
# 创建示例数据集
df1 = pd.DataFrame({
'A': range(1, 6),
'B': range(10, 60, 10)
}, index=['a', 'b', 'c', 'd', 'e'])
df2 = pd.DataFrame({
'A': range(3, 8),
'C': range(30, 80, 10)
}, index=['c', 'd', 'e', 'f', 'g'])
print("df1:")
print(df1)
print("\ndf2:")
print(df2)
使用 loc[] 进行标签索引交叉
# 使用 loc[] 进行标签索引交叉
index_intersection = df1.index.intersection(df2.index)
result = df1.loc[index_intersection]
print("索引交叉结果:")
print(result)
# 具体值索引交叉
result_lc = df1.loc[['a', 'c', 'e'], ['A']]
print("\n具体行和列的交叉选择:")
print(result_lc)
使用 iloc[] 进行位置索引交叉
# 使用整数位置进行索引交叉
result_iloc = df1.iloc[0:3, 0:1] # 前3行,第1列
print("位置索引交叉:")
print(result_iloc)
ix[] (已废弃,但了解)
# 注意:ix[] 在较新版本中已废弃,推荐使用 loc[] 和 iloc[] # 旧版本中可以使用 # result_ix = df1.ix[['a', 'c'], ['A']]
使用 xs() 进行交叉选择
# 创建多层索引数据
arrays = [
['A', 'A', 'B', 'B', 'C', 'C'],
['x', 'y', 'x', 'y', 'x', 'y']
]
index = pd.MultiIndex.from_arrays(arrays, names=['first', 'second'])
multi_df = pd.DataFrame({
'value1': range(10, 70, 10),
'value2': range(100, 160, 10)
}, index=index)
print("多层索引DataFrame:")
print(multi_df)
print()
# 使用 xs() 进行索引交叉
result_xs = multi_df.xs(key='A', level='first')
print("选择 first='A' 的所有数据:")
print(result_xs)
# 交叉选择特定值
result_xs2 = multi_df.xs(key=('A', 'x'))
print("\n选择 first='A', second='x' 的数据:")
print(result_xs2)
实际应用案例
# 更实际的案例 - 销售数据分析
# 创建销售数据
sales_data = {
'date': pd.date_range('2024-01-01', periods=10, freq='D'),
'product': ['A', 'B', 'A', 'C', 'B', 'A', 'C', 'B', 'A', 'C'],
'sales': [100, 150, 120, 180, 130, 110, 200, 160, 90, 175],
'quantity': [10, 15, 12, 18, 13, 11, 20, 16, 9, 17]
}
df_sales = pd.DataFrame(sales_data)
df_sales.set_index('date', inplace=True)
print("销售数据:")
print(df_sales)
print()
# 索引交叉分析
# 选择特定日期范围
date_range = pd.date_range('2024-01-03', '2024-01-07')
sales_period = df_sales.loc[date_range]
print("特定日期的销售数据:")
print(sales_period)
print()
# 选择特定产品在特定日期范围的数据
product_A_sales = df_sales.loc[
(df_sales.index >= '2024-01-03') &
(df_sales.index <= '2024-01-07') &
(df_sales['product'] == 'A')
]
print("产品A在特定日期范围的销售:")
print(product_A_sales)
高级索引交叉技巧
# 条件索引交叉
# 创建更多数据
df_high = pd.DataFrame({
'score': np.random.randint(60, 100, 10)
}, index=pd.date_range('2024-01-01', periods=10, freq='D'))
print("成绩数据:")
print(df_high)
print()
# 布尔索引交叉
high_scores = df_high[df_high['score'] > 80]
print("成绩 > 80 的数据:")
print(high_scores)
print()
# 多条件交叉
combined_condition = df_high[
(df_high['score'] > 70) &
(df_high.index >= '2024-01-05')
]
print("综合条件筛选:")
print(combined_condition)
实用技巧总结
# 索引交叉常用方法
# 1. 找出共同索引
common_index = df1.index & df2.index
print("共同索引:", common_index)
# 2. 找出不同索引
diff_index = df1.index ^ df2.index
print("不同索引:", diff_index)
# 3. 合并索引
union_index = df1.index | df2.index
print("合并索引:", union_index)
# 4. 使用 query() 方法
result_query = df_sales.query('sales > 150 & quantity > 15')
print("\n使用query筛选:")
print(result_query)
# 5. 动态索引交叉
def dynamic_index_cross(df, start_date, end_date, conditions=None):
"""
动态索引交叉函数
"""
mask = (df.index >= start_date) & (df.index <= end_date)
if conditions:
for col, value in conditions.items():
mask &= (df[col] == value)
return df[mask]
# 使用示例
result_dynamic = dynamic_index_cross(
df_sales,
'2024-01-05',
'2024-01-10',
{'product': 'B'}
)
print("\n动态索引交叉结果:")
print(result_dynamic)
- loc[]:基于标签索引
- iloc[]:基于整数位置索引
- xs():处理多层索引
- 布尔索引:条件筛选
- 索引运算:&, |, ^ 进行索引操作
这些方法在实际数据分析中非常实用,可以根据具体需求选择合适的方法。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播