Python pandas 按多个索引范围切片数据框
- 2025-03-21 09:05:00
- admin 原创
- 36
问题描述:
按更多索引范围(例如10:12
和25:28
)对数据框进行切分的 Python 方法是什么?
我想要一种更优雅的方式:
df = pd.DataFrame({'a':range(10,100)})
df.iloc[[i for i in range(10,12)] + [i for i in range(25,28)]]
结果:
a
10 20
11 21
25 35
26 36
27 37
像这样的事情会更加优雅:
df.iloc[(10:12, 25:28)]
解决方案 1:
您可以使用 numpy 的r_
“切片技巧”:
df = pd.DataFrame({'a':range(10,100)})
df.iloc[pd.np.r_[10:12, 25:28]]
注意:这现在会给出警告The pandas.np module is deprecated and will be removed from pandas in a future version. Import numpy directly instead
。为此,您可以import numpy as np
按以下方式切片:
df.iloc[np.r_[10:12, 25:28]]
得出:
a
10 20
11 21
25 35
26 36
27 37
解决方案 2:
您可以利用 pandas isin 函数。
df = pd.DataFrame({'a':range(10,100)})
ls = [i for i in range(10,12)] + [i for i in range(25,28)]
df[df.index.isin(ls)]
a
10 20
11 21
25 35
26 36
27 37
解决方案 3:
基于 @KevinOelen 对 Panda 的 isin 函数的使用,这里有一个 Pythonic 方法(Python 3.8)来浏览 Pandas DataFrame 或 GeoPandas GeoDataFrame,只显示头部和尾部的几行。此方法不需要导入 numpy。
要使用,只需调用glance(your_df)。文档字符串中有附加说明。
import pandas as pd
import geopandas as gpd # if not needed, remove gpd.GeoDataFrame from the type hinting and no need to import Union
from typing import Union
def glance(df: Union[pd.DataFrame, gpd.GeoDataFrame], size: int = 2) -> None:
""" Provides a shortened head and tail summary of a Dataframe or GeoDataFrame in Jupyter Notebook or Lab.
Usage
----------
# default glance (2 head rows, 2 tail rows)
glance( df )
# glance defined number of rows in head and tail (3 head rows, 3 tails rows)
glance( df, size=3 )
Parameters
----------
:param df: Union[pd.DataFrame, gpd.GeoDataFrame]: A (Geo)Pandas data frame to glance at.
:param size: int: The number of rows in the head and tail to display, total rows will be double provided size.
:return: None: Displays result in Notebook or Lab.
"""
# min and max of the provided dataframe index
min_ = df.index.min()
max_ = df.index.max()
# define slice
sample = [i for i in range(min_, size)] + [i for i in range(max_ - size, max_)]
# slice
df = df[df.index.isin(sample)]
# display
display( df )
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD