vibespatial.api.geoseries¶
Classes¶
A Series object designed to store shapely geometry objects. |
Module Contents¶
- class vibespatial.api.geoseries.GeoSeries(data=None, index=None, crs: Any | None = None, **kwargs)¶
A Series object designed to store shapely geometry objects.
Parameters¶
- dataarray-like, dict, scalar value
The geometries to store in the GeoSeries.
- indexarray-like or Index
The index for the GeoSeries.
- crsvalue (optional)
Coordinate Reference System of the geometry objects. Can be anything accepted by
pyproj.CRS.from_user_input(), such as an authority string (eg “EPSG:4326”) or a WKT string.- kwargs
- Additional arguments passed to the Series constructor,
e.g.
name.
Examples¶
>>> from shapely.geometry import Point >>> s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)]) >>> s 0 POINT (1 1) 1 POINT (2 2) 2 POINT (3 3) dtype: geometry
>>> s = geopandas.GeoSeries( ... [Point(1, 1), Point(2, 2), Point(3, 3)], crs="EPSG:3857" ... ) >>> s.crs <Projected CRS: EPSG:3857> Name: WGS 84 / Pseudo-Mercator Axis Info [cartesian]: - X[east]: Easting (metre) - Y[north]: Northing (metre) Area of Use: - name: World - 85°S to 85°N - bounds: (-180.0, -85.06, 180.0, 85.06) Coordinate Operation: - name: Popular Visualisation Pseudo-Mercator - method: Popular Visualisation Pseudo Mercator Datum: World Geodetic System 1984 - Ellipsoid: WGS 84 - Prime Meridian: Greenwich
>>> s = geopandas.GeoSeries( ... [Point(1, 1), Point(2, 2), Point(3, 3)], index=["a", "b", "c"], crs=4326 ... ) >>> s a POINT (1 1) b POINT (2 2) c POINT (3 3) dtype: geometry
>>> s.crs <Geographic 2D CRS: EPSG:4326> Name: WGS 84 Axis Info [ellipsoidal]: - Lat[north]: Geodetic latitude (degree) - Lon[east]: Geodetic longitude (degree) Area of Use: - name: World. - bounds: (-180.0, -90.0, 180.0, 90.0) Datum: World Geodetic System 1984 ensemble - Ellipsoid: WGS 84 - Prime Meridian: Greenwich
See Also¶
GeoDataFrame pandas.Series
- property x: pandas.Series¶
Return the x location of point geometries in a GeoSeries.
Returns¶
pandas.Series
Examples¶
>>> from shapely.geometry import Point >>> s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)]) >>> s.x 0 1.0 1 2.0 2 3.0 dtype: float64
See Also¶
GeoSeries.y GeoSeries.z
- property y: pandas.Series¶
Return the y location of point geometries in a GeoSeries.
Returns¶
pandas.Series
Examples¶
>>> from shapely.geometry import Point >>> s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)]) >>> s.y 0 1.0 1 2.0 2 3.0 dtype: float64
See Also¶
GeoSeries.x GeoSeries.z GeoSeries.m
- property z: pandas.Series¶
Return the z location of point geometries in a GeoSeries.
Returns¶
pandas.Series
Examples¶
>>> from shapely.geometry import Point >>> s = geopandas.GeoSeries([Point(1, 1, 1), Point(2, 2, 2), Point(3, 3, 3)]) >>> s.z 0 1.0 1 2.0 2 3.0 dtype: float64
See Also¶
GeoSeries.x GeoSeries.y GeoSeries.m
- property m: pandas.Series¶
Return the m coordinate of point geometries in a GeoSeries.
Requires Shapely >= 2.1.
Added in version 1.1.0.
Returns¶
pandas.Series
Examples¶
>>> from shapely.geometry import Point >>> s = geopandas.GeoSeries.from_wkt( ... [ ... "POINT M (2 3 5)", ... "POINT M (1 2 3)", ... ] ... ) >>> s 0 POINT M (2 3 5) 1 POINT M (1 2 3) dtype: geometry
>>> s.m 0 5.0 1 3.0 dtype: float64
See Also¶
GeoSeries.x GeoSeries.y GeoSeries.z
- classmethod from_file(filename: os.PathLike | IO, **kwargs) GeoSeries¶
Alternate constructor to create a
GeoSeriesfrom a file.Can load a
GeoSeriesfrom a file from any format recognized by pyogrio. See http://pyogrio.readthedocs.io/ for details. From a file with attributes loads only geometry column. Note that to do that, GeoPandas first loads the whole GeoDataFrame.Parameters¶
- filenamestr
File path or file handle to read from. Depending on which kwargs are included, the content of filename may vary. See
pyogrio.read_dataframe()for usage details.- kwargskey-word arguments
These arguments are passed to
pyogrio.read_dataframe(), and can be used to access multi-layer data, data stored within archives (zip files), etc.
Examples¶
>>> import geodatasets >>> path = geodatasets.get_path('nybb') >>> s = geopandas.GeoSeries.from_file(path) >>> s 0 MULTIPOLYGON (((970217.022 145643.332, 970227.... 1 MULTIPOLYGON (((1029606.077 156073.814, 102957... 2 MULTIPOLYGON (((1021176.479 151374.797, 102100... 3 MULTIPOLYGON (((981219.056 188655.316, 980940.... 4 MULTIPOLYGON (((1012821.806 229228.265, 101278... Name: geometry, dtype: geometry
See Also¶
read_file : read file to GeoDataFrame
- classmethod from_wkb(data, index=None, crs: Any | None = None, on_invalid='raise', **kwargs) GeoSeries¶
Alternate constructor to create a
GeoSeriesfrom a list or array of WKB objects.Parameters¶
- dataarray-like or Series
Series, list or array of WKB objects
- indexarray-like or Index
The index for the GeoSeries.
- crsvalue, optional
Coordinate Reference System of the geometry objects. Can be anything accepted by
pyproj.CRS.from_user_input(), such as an authority string (eg “EPSG:4326”) or a WKT string.- on_invalid: {“raise”, “warn”, “ignore”}, default “raise”
raise: an exception will be raised if a WKB input geometry is invalid.
warn: a warning will be raised and invalid WKB geometries will be returned as None.
ignore: invalid WKB geometries will be returned as None without a warning.
fix: an effort is made to fix invalid input geometries (e.g. close unclosed rings). If this is not possible, they are returned as
Nonewithout a warning. Requires GEOS >= 3.11 and shapely >= 2.1.
- kwargs
Additional arguments passed to the Series constructor, e.g.
name.
Returns¶
GeoSeries
See Also¶
GeoSeries.from_wkt
Examples¶
>>> wkbs = [ ... ( ... b"\x01\x01\x00\x00\x00\x00\x00\x00\x00" ... b"\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?" ... ), ... ( ... b"\x01\x01\x00\x00\x00\x00\x00\x00\x00" ... b"\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x00@" ... ), ... ( ... b"\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00" ... b"\x00\x08@\x00\x00\x00\x00\x00\x00\x08@" ... ), ... ] >>> s = geopandas.GeoSeries.from_wkb(wkbs) >>> s 0 POINT (1 1) 1 POINT (2 2) 2 POINT (3 3) dtype: geometry
- classmethod from_wkt(data, index=None, crs: Any | None = None, on_invalid='raise', **kwargs) GeoSeries¶
Alternate constructor to create a
GeoSeriesfrom a list or array of WKT objects.Parameters¶
- dataarray-like, Series
Series, list, or array of WKT objects
- indexarray-like or Index
The index for the GeoSeries.
- crsvalue, optional
Coordinate Reference System of the geometry objects. Can be anything accepted by
pyproj.CRS.from_user_input(), such as an authority string (eg “EPSG:4326”) or a WKT string.- on_invalid{“raise”, “warn”, “ignore”}, default “raise”
raise: an exception will be raised if a WKT input geometry is invalid.
warn: a warning will be raised and invalid WKT geometries will be returned as
None.ignore: invalid WKT geometries will be returned as
Nonewithout a warning.fix: an effort is made to fix invalid input geometries (e.g. close unclosed rings). If this is not possible, they are returned as
Nonewithout a warning. Requires GEOS >= 3.11 and shapely >= 2.1.
- kwargs
Additional arguments passed to the Series constructor, e.g.
name.
Returns¶
GeoSeries
See Also¶
GeoSeries.from_wkb
Examples¶
>>> wkts = [ ... 'POINT (1 1)', ... 'POINT (2 2)', ... 'POINT (3 3)', ... ] >>> s = geopandas.GeoSeries.from_wkt(wkts) >>> s 0 POINT (1 1) 1 POINT (2 2) 2 POINT (3 3) dtype: geometry
- classmethod from_xy(x, y, z=None, index=None, crs=None, **kwargs) GeoSeries¶
Alternate constructor to create a
GeoSeriesof Point geometries from lists or arrays of x, y(, z) coordinates.In case of geographic coordinates, it is assumed that longitude is captured by
xcoordinates and latitude byy.Parameters¶
x, y, z : iterable index : array-like or Index, optional
The index for the GeoSeries. If not given and all coordinate inputs are Series with an equal index, that index is used.
- crsvalue, optional
Coordinate Reference System of the geometry objects. Can be anything accepted by
pyproj.CRS.from_user_input(), such as an authority string (eg “EPSG:4326”) or a WKT string.- **kwargs
Additional arguments passed to the Series constructor, e.g.
name.
Returns¶
GeoSeries
See Also¶
GeoSeries.from_wkt points_from_xy
Examples¶
>>> x = [2.5, 5, -3.0] >>> y = [0.5, 1, 1.5] >>> s = geopandas.GeoSeries.from_xy(x, y, crs="EPSG:4326") >>> s 0 POINT (2.5 0.5) 1 POINT (5 1) 2 POINT (-3 1.5) dtype: geometry
- classmethod from_arrow(arr, **kwargs) GeoSeries¶
Construct a GeoSeries from an Arrow array object with a GeoArrow extension type.
See https://geoarrow.org/ for details on the GeoArrow specification.
This functions accepts any Arrow array object implementing the Arrow PyCapsule Protocol (i.e. having an
__arrow_c_array__method).Added in version 1.0.
Parameters¶
- arrpyarrow.Array, Arrow array
Any array object implementing the Arrow PyCapsule Protocol (i.e. has an
__arrow_c_array__or__arrow_c_stream__method). The type of the array should be one of the geoarrow geometry types.- **kwargs
Other parameters passed to the GeoSeries constructor.
Returns¶
GeoSeries
See Also¶
GeoSeries.to_arrow
Examples¶
>>> import geoarrow.pyarrow as ga >>> array = ga.as_geoarrow( ... [None, "POLYGON ((0 0, 1 1, 0 1, 0 0))", "LINESTRING (0 0, -1 1, 0 -1)"]) >>> geoseries = geopandas.GeoSeries.from_arrow(array) >>> geoseries 0 None 1 POLYGON ((0 0, 1 1, 0 1, 0 0)) 2 LINESTRING (0 0, -1 1, 0 -1) dtype: geometry
- to_file(filename: os.PathLike | IO, driver: str | None = None, index: bool | None = None, **kwargs)¶
Write the
GeoSeriesto a file.By default, an ESRI shapefile is written, but any OGR data source supported by Pyogrio or Fiona can be written.
Parameters¶
- filenamestring
File path or file handle to write to. The path may specify a GDAL VSI scheme.
- driverstring, default None
The OGR format driver used to write the vector file. If not specified, it attempts to infer it from the file extension. If no extension is specified, it saves ESRI Shapefile to a folder.
- indexbool, default None
If True, write index into one or more columns (for MultiIndex). Default None writes the index into one or more columns only if the index is named, is a MultiIndex, or has a non-integer data type. If False, no index is written.
Added in version 0.7: Previously the index was not written.
- modestring, default ‘w’
The write mode, ‘w’ to overwrite the existing file and ‘a’ to append. Not all drivers support appending. The drivers that support appending are listed in fiona.supported_drivers or https://github.com/Toblerity/Fiona/blob/master/fiona/drvsupport.py
- crspyproj.CRS, default None
If specified, the CRS is passed to Fiona to better control how the file is written. If None, GeoPandas will determine the crs based on crs df attribute. The value can be anything accepted by
pyproj.CRS.from_user_input(), such as an authority string (eg “EPSG:4326”) or a WKT string. The keyword is not supported for the “pyogrio” engine.- enginestr, “pyogrio” or “fiona”
The underlying library that is used to write the file. Currently, the supported options are “pyogrio” and “fiona”. Defaults to “pyogrio” if installed, otherwise tries “fiona”.
- **kwargs :
Keyword args to be passed to the engine, and can be used to write to multi-layer data, store data within archives (zip files), etc. In case of the “pyogrio” engine, the keyword arguments are passed to pyogrio.write_dataframe. In case of the “fiona” engine, the keyword arguments are passed to fiona.open`. For more information on possible keywords, type:
import pyogrio; help(pyogrio.write_dataframe).
See Also¶
GeoDataFrame.to_file : write GeoDataFrame to file read_file : read file to GeoDataFrame
Examples¶
>>> s.to_file('series.shp')
>>> s.to_file('series.gpkg', driver='GPKG', layer='name1')
>>> s.to_file('series.geojson', driver='GeoJSON')
- property loc¶
Access a group of rows and columns by label(s) or a boolean array.
.loc[]is primarily label based, but may also be used with a boolean array.Allowed inputs are:
A single label, e.g.
5or'a', (note that5is interpreted as a label of the index, and never as an integer position along the index).A list or array of labels, e.g.
['a', 'b', 'c'].A slice object with labels, e.g.
'a':'f'.Warning
Note that contrary to usual python slices, both the start and the stop are included
A boolean array of the same length as the axis being sliced, e.g.
[True, False, True].An alignable boolean Series. The index of the key will be aligned before masking.
An alignable Index. The Index of the returned selection will be the input.
A
callablefunction with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above)
See more at Selection by Label.
Raises¶
- KeyError
If any items are not found.
- IndexingError
If an indexed key is passed and its index is unalignable to the frame index.
See Also¶
DataFrame.at : Access a single value for a row/column label pair. DataFrame.iloc : Access group of rows and columns by integer position(s). DataFrame.xs : Returns a cross-section (row(s) or column(s)) from the
Series/DataFrame.
Series.loc : Access group of values using labels.
Examples¶
Getting values
>>> df = pd.DataFrame( ... [[1, 2], [4, 5], [7, 8]], ... index=["cobra", "viper", "sidewinder"], ... columns=["max_speed", "shield"], ... ) >>> df max_speed shield cobra 1 2 viper 4 5 sidewinder 7 8
Single label. Note this returns the row as a Series.
>>> df.loc["viper"] max_speed 4 shield 5 Name: viper, dtype: int64
List of labels. Note using
[[]]returns a DataFrame.>>> df.loc[["viper", "sidewinder"]] max_speed shield viper 4 5 sidewinder 7 8
Single label for row and column
>>> df.loc["cobra", "shield"] np.int64(2)
Slice with labels for row and single label for column. As mentioned above, note that both the start and stop of the slice are included.
>>> df.loc["cobra":"viper", "max_speed"] cobra 1 viper 4 Name: max_speed, dtype: int64
Boolean list with the same length as the row axis
>>> df.loc[[False, False, True]] max_speed shield sidewinder 7 8
Alignable boolean Series:
>>> df.loc[ ... pd.Series([False, True, False], index=["viper", "sidewinder", "cobra"]) ... ] max_speed shield sidewinder 7 8
Index (same behavior as
df.reindex)>>> df.loc[pd.Index(["cobra", "viper"], name="foo")] max_speed shield foo cobra 1 2 viper 4 5
Conditional that returns a boolean Series
>>> df.loc[df["shield"] > 6] max_speed shield sidewinder 7 8
Conditional that returns a boolean Series with column labels specified
>>> df.loc[df["shield"] > 6, ["max_speed"]] max_speed sidewinder 7
Multiple conditional using
&that returns a boolean Series>>> df.loc[(df["max_speed"] > 1) & (df["shield"] < 8)] max_speed shield viper 4 5
Multiple conditional using
|that returns a boolean Series>>> df.loc[(df["max_speed"] > 4) | (df["shield"] < 5)] max_speed shield cobra 1 2 sidewinder 7 8
Please ensure that each condition is wrapped in parentheses
(). See the user guide for more details and explanations of Boolean indexing.Note
If you find yourself using 3 or more conditionals in
.loc[], consider using advanced indexing.See below for using
.loc[]on MultiIndex DataFrames.Callable that returns a boolean Series
>>> df.loc[lambda df: df["shield"] == 8] max_speed shield sidewinder 7 8
Setting values
Set value for all items matching the list of labels
>>> df.loc[["viper", "sidewinder"], ["shield"]] = 50 >>> df max_speed shield cobra 1 2 viper 4 50 sidewinder 7 50
Set value for an entire row
>>> df.loc["cobra"] = 10 >>> df max_speed shield cobra 10 10 viper 4 50 sidewinder 7 50
Set value for an entire column
>>> df.loc[:, "max_speed"] = 30 >>> df max_speed shield cobra 30 10 viper 30 50 sidewinder 30 50
Set value for rows matching callable condition
>>> df.loc[df["shield"] > 35] = 0 >>> df max_speed shield cobra 30 10 viper 0 0 sidewinder 0 0
Add value matching location
>>> df.loc["viper", "shield"] += 5 >>> df max_speed shield cobra 30 10 viper 0 5 sidewinder 0 0
Setting using a
Seriesor aDataFramesets the values matching the index labels, not the index positions.>>> shuffled_df = df.loc[["viper", "cobra", "sidewinder"]] >>> df.loc[:] += shuffled_df >>> df max_speed shield cobra 60 20 viper 0 10 sidewinder 0 0
Getting values on a DataFrame with an index that has integer labels
Another example using integers for the index
>>> df = pd.DataFrame( ... [[1, 2], [4, 5], [7, 8]], ... index=[7, 8, 9], ... columns=["max_speed", "shield"], ... ) >>> df max_speed shield 7 1 2 8 4 5 9 7 8
Slice with integer labels for rows. As mentioned above, note that both the start and stop of the slice are included.
>>> df.loc[7:9] max_speed shield 7 1 2 8 4 5 9 7 8
Getting values with a MultiIndex
A number of examples using a DataFrame with a MultiIndex
>>> tuples = [ ... ("cobra", "mark i"), ... ("cobra", "mark ii"), ... ("sidewinder", "mark i"), ... ("sidewinder", "mark ii"), ... ("viper", "mark ii"), ... ("viper", "mark iii"), ... ] >>> index = pd.MultiIndex.from_tuples(tuples) >>> values = [[12, 2], [0, 4], [10, 20], [1, 4], [7, 1], [16, 36]] >>> df = pd.DataFrame(values, columns=["max_speed", "shield"], index=index) >>> df max_speed shield cobra mark i 12 2 mark ii 0 4 sidewinder mark i 10 20 mark ii 1 4 viper mark ii 7 1 mark iii 16 36
Single label. Note this returns a DataFrame with a single index.
>>> df.loc["cobra"] max_speed shield mark i 12 2 mark ii 0 4
Single index tuple. Note this returns a Series.
>>> df.loc[("cobra", "mark ii")] max_speed 0 shield 4 Name: (cobra, mark ii), dtype: int64
Single label for row and column. Similar to passing in a tuple, this returns a Series.
>>> df.loc["cobra", "mark i"] max_speed 12 shield 2 Name: (cobra, mark i), dtype: int64
Single tuple. Note using
[[]]returns a DataFrame.>>> df.loc[[("cobra", "mark ii")]] max_speed shield cobra mark ii 0 4
Single tuple for the index with a single label for the column
>>> df.loc[("cobra", "mark i"), "shield"] np.int64(2)
Slice from index tuple to single label
>>> df.loc[("cobra", "mark i") : "viper"] max_speed shield cobra mark i 12 2 mark ii 0 4 sidewinder mark i 10 20 mark ii 1 4 viper mark ii 7 1 mark iii 16 36
Slice from index tuple to index tuple
>>> df.loc[("cobra", "mark i") : ("viper", "mark ii")] max_speed shield cobra mark i 12 2 mark ii 0 4 sidewinder mark i 10 20 mark ii 1 4 viper mark ii 7 1
Please see the user guide for more details and explanations of advanced indexing.
Assignment with Series
When assigning a Series to .loc[row_indexer, col_indexer], pandas aligns the Series by index labels, not by order or position.
Series assignment with .loc and index alignment:
>>> df = pd.DataFrame({"A": [1, 2, 3]}, index=[0, 1, 2]) >>> s = pd.Series([10, 20], index=[1, 0]) # Note reversed order >>> df.loc[:, "B"] = s # Aligns by index, not order >>> df A B 0 1 20.0 1 2 10.0 2 3 NaN
- property iloc¶
Purely integer-location based indexing for selection by position.
Changed in version 3.0: Callables which return a tuple are deprecated as input.
.iloc[]is primarily integer position based (from0tolength-1of the axis), but may also be used with a boolean array.Allowed inputs are:
An integer, e.g.
5.A list or array of integers, e.g.
[4, 3, 0].A slice object with ints, e.g.
1:7.A boolean array.
A
callablefunction with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above). This is useful in method chains, when you don’t have a reference to the calling object, but would like to base your selection on some value.A tuple of row and column indexes. The tuple elements consist of one of the above inputs, e.g.
(0, 1).
.ilocwill raiseIndexErrorif a requested indexer is out-of-bounds, except slice indexers which allow out-of-bounds indexing (this conforms with python/numpy slice semantics).See more at Selection by Position.
See Also¶
DataFrame.iat : Fast integer location scalar accessor. DataFrame.loc : Purely label-location based indexer for selection by label. Series.iloc : Purely integer-location based indexing for
selection by position.
Examples¶
>>> mydict = [ ... {"a": 1, "b": 2, "c": 3, "d": 4}, ... {"a": 100, "b": 200, "c": 300, "d": 400}, ... {"a": 1000, "b": 2000, "c": 3000, "d": 4000}, ... ] >>> df = pd.DataFrame(mydict) >>> df a b c d 0 1 2 3 4 1 100 200 300 400 2 1000 2000 3000 4000
Indexing just the rows
With a scalar integer.
>>> type(df.iloc[0]) <class 'pandas.Series'> >>> df.iloc[0] a 1 b 2 c 3 d 4 Name: 0, dtype: int64
With a list of integers.
>>> df.iloc[[0]] a b c d 0 1 2 3 4 >>> type(df.iloc[[0]]) <class 'pandas.DataFrame'>
>>> df.iloc[[0, 1]] a b c d 0 1 2 3 4 1 100 200 300 400
With a slice object.
>>> df.iloc[:3] a b c d 0 1 2 3 4 1 100 200 300 400 2 1000 2000 3000 4000
With a boolean mask the same length as the index.
>>> df.iloc[[True, False, True]] a b c d 0 1 2 3 4 2 1000 2000 3000 4000
With a callable, useful in method chains. The x passed to the
lambdais the DataFrame being sliced. This selects the rows whose index label even.>>> df.iloc[lambda x: x.index % 2 == 0] a b c d 0 1 2 3 4 2 1000 2000 3000 4000
Indexing both axes
You can mix the indexer types for the index and columns. Use
:to select the entire axis.With scalar integers.
>>> df.iloc[0, 1] np.int64(2)
With lists of integers.
>>> df.iloc[[0, 2], [1, 3]] b d 0 2 4 2 2000 4000
With slice objects.
>>> df.iloc[1:3, 0:3] a b c 1 100 200 300 2 1000 2000 3000
With a boolean array whose length matches the columns.
>>> df.iloc[:, [True, False, True, False]] a c 0 1 3 1 100 300 2 1000 3000
With a callable function that expects the Series or DataFrame.
>>> df.iloc[:, lambda df: [0, 2]] a c 0 1 3 1 100 300 2 1000 3000
- property at¶
Access a single value for a row/column label pair.
Similar to
loc, in that both provide label-based lookups. Useatif you only need to get or set a single value in a DataFrame or Series.Raises¶
- KeyError
If getting a value and ‘label’ does not exist in a DataFrame or Series.
- ValueError
If row/column label pair is not a tuple or if any label from the pair is not a scalar for DataFrame. If label is list-like (excluding NamedTuple) for Series.
See Also¶
DataFrame.at : Access a single value for a row/column pair by label. DataFrame.iat : Access a single value for a row/column pair by integer
position.
DataFrame.loc : Access a group of rows and columns by label(s). DataFrame.iloc : Access a group of rows and columns by integer
position(s).
Series.at : Access a single value by label. Series.iat : Access a single value by integer position. Series.loc : Access a group of rows by label(s). Series.iloc : Access a group of rows by integer position(s).
Notes¶
See Fast scalar value getting and setting for more details.
Examples¶
>>> df = pd.DataFrame( ... [[0, 2, 3], [0, 4, 1], [10, 20, 30]], ... index=[4, 5, 6], ... columns=["A", "B", "C"], ... ) >>> df A B C 4 0 2 3 5 0 4 1 6 10 20 30
Get value at specified row/column pair
>>> df.at[4, "B"] np.int64(2)
Set value at specified row/column pair
>>> df.at[4, "B"] = 10 >>> df.at[4, "B"] np.int64(10)
Get value within a Series
>>> df.loc[5].at["B"] np.int64(4)
- property iat¶
Access a single value for a row/column pair by integer position.
Similar to
iloc, in that both provide integer-based lookups. Useiatif you only need to get or set a single value in a DataFrame or Series.Raises¶
- IndexError
When integer position is out of bounds.
See Also¶
DataFrame.at : Access a single value for a row/column label pair. DataFrame.loc : Access a group of rows and columns by label(s). DataFrame.iloc : Access a group of rows and columns by integer position(s).
Examples¶
>>> df = pd.DataFrame( ... [[0, 2, 3], [0, 4, 1], [10, 20, 30]], columns=["A", "B", "C"] ... ) >>> df A B C 0 0 2 3 1 0 4 1 2 10 20 30
Get value at specified row/column pair
>>> df.iat[1, 2] np.int64(1)
Set value at specified row/column pair
>>> df.iat[1, 2] = 10 >>> df.iat[1, 2] np.int64(10)
Get value within a series
>>> df.loc[0].iat[1] np.int64(2)
- sort_index(*args, **kwargs)¶
Sort Series by index labels.
Returns a new Series sorted by label if inplace argument is
False, otherwise updates the original series and returns None.Parameters¶
- axis{0 or ‘index’}
Unused. Parameter needed for compatibility with DataFrame.
- levelint, optional
If not None, sort on values in specified index level(s).
- ascendingbool or list-like of bools, default True
Sort ascending vs. descending. When the index is a MultiIndex the sort direction can be controlled for each level individually.
- inplacebool, default False
If True, perform operation in-place.
- kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, default ‘quicksort’
Choice of sorting algorithm. See also
numpy.sort()for more information. ‘mergesort’ and ‘stable’ are the only stable algorithms. For DataFrames, this option is only applied when sorting on a single column or label.- na_position{‘first’, ‘last’}, default ‘last’
If ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end. Not implemented for MultiIndex.
- sort_remainingbool, default True
If True and sorting by level and index is multilevel, sort by other levels too (in order) after sorting by specified level.
- ignore_indexbool, default False
If True, the resulting axis will be labeled 0, 1, …, n - 1.
- keycallable, optional
If not None, apply the key function to the index values before sorting. This is similar to the key argument in the builtin
sorted()function, with the notable difference that this key function should be vectorized. It should expect anIndexand return anIndexof the same shape.
Returns¶
- Series or None
The original Series sorted by the labels or None if
inplace=True.
See Also¶
DataFrame.sort_index: Sort DataFrame by the index. DataFrame.sort_values: Sort DataFrame by the value. Series.sort_values : Sort Series by the value.
Examples¶
>>> s = pd.Series(["a", "b", "c", "d"], index=[3, 2, 1, 4]) >>> s.sort_index() 1 c 2 b 3 a 4 d dtype: str
Sort Descending
>>> s.sort_index(ascending=False) 4 d 3 a 2 b 1 c dtype: str
By default NaNs are put at the end, but use na_position to place them at the beginning
>>> s = pd.Series(["a", "b", "c", "d"], index=[3, 2, 1, np.nan]) >>> s.sort_index(na_position="first") NaN d 1.0 c 2.0 b 3.0 a dtype: str
Specify index level to sort
>>> arrays = [ ... np.array(["qux", "qux", "foo", "foo", "baz", "baz", "bar", "bar"]), ... np.array(["two", "one", "two", "one", "two", "one", "two", "one"]), ... ] >>> s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8], index=arrays) >>> s.sort_index(level=1) bar one 8 baz one 6 foo one 4 qux one 2 bar two 7 baz two 5 foo two 3 qux two 1 dtype: int64
Does not sort by remaining levels when sorting by levels
>>> s.sort_index(level=1, sort_remaining=False) qux one 2 foo one 4 baz one 6 bar one 8 qux two 1 foo two 3 baz two 5 bar two 7 dtype: int64
Apply a key function before sorting
>>> s = pd.Series([1, 2, 3, 4], index=["A", "b", "C", "d"]) >>> s.sort_index(key=lambda x: x.str.lower()) A 1 b 2 C 3 d 4 dtype: int64
- take(*args, **kwargs)¶
Return the elements in the given positional indices along an axis.
This means that we are not indexing according to actual values in the index attribute of the object. We are indexing according to the actual position of the element in the object.
Parameters¶
- indicesarray-like
An array of ints indicating which positions to take.
- axis{0 or ‘index’, 1 or ‘columns’}, default 0
The axis on which to select elements.
0means that we are selecting rows,1means that we are selecting columns. For Series this parameter is unused and defaults to 0.- **kwargs
For compatibility with
numpy.take(). Has no effect on the output.
Returns¶
- same type as caller
An array-like containing the elements taken from the object.
See Also¶
DataFrame.loc : Select a subset of a DataFrame by labels. DataFrame.iloc : Select a subset of a DataFrame by positions. numpy.take : Take elements from an array along an axis.
Examples¶
>>> df = pd.DataFrame( ... [ ... ("falcon", "bird", 389.0), ... ("parrot", "bird", 24.0), ... ("lion", "mammal", 80.5), ... ("monkey", "mammal", np.nan), ... ], ... columns=["name", "class", "max_speed"], ... index=[0, 2, 3, 1], ... ) >>> df name class max_speed 0 falcon bird 389.0 2 parrot bird 24.0 3 lion mammal 80.5 1 monkey mammal NaN
Take elements at positions 0 and 3 along the axis 0 (default).
Note how the actual indices selected (0 and 1) do not correspond to our selected indices 0 and 3. That’s because we are selecting the 0th and 3rd rows, not rows whose indices equal 0 and 3.
>>> df.take([0, 3]) name class max_speed 0 falcon bird 389.0 1 monkey mammal NaN
Take elements at indices 1 and 2 along the axis 1 (column selection).
>>> df.take([1, 2], axis=1) class max_speed 0 bird 389.0 2 bird 24.0 3 mammal 80.5 1 mammal NaN
We may take elements using negative integers for positive indices, starting from the end of the object, just like with Python lists.
>>> df.take([-1, -2]) name class max_speed 1 monkey mammal NaN 3 lion mammal 80.5
- copy(*args, **kwargs)¶
Make a copy of this object’s indices and data.
When
deep=True(default), a new object will be created with a copy of the calling object’s data and indices. Modifications to the data or indices of the copy will not be reflected in the original object (see notes below).When
deep=False, a new object will be created without copying the calling object’s data or index (only references to the data and index are copied). With Copy-on-Write, changes to the original will not be reflected in the shallow copy (and vice versa). The shallow copy uses a lazy (deferred) copy mechanism that copies the data only when any changes to the original or shallow copy are made, ensuring memory efficiency while maintaining data integrity.Note
In pandas versions prior to 3.0, the default behavior without Copy-on-Write was different: changes to the original were reflected in the shallow copy (and vice versa). See the Copy-on-Write user guide for more information.
Parameters¶
- deepbool, default True
Make a deep copy, including a copy of the data and the indices. With
deep=Falseneither the indices nor the data are copied.
Returns¶
- Series or DataFrame
Object type matches caller.
See Also¶
copy.copy : Return a shallow copy of an object. copy.deepcopy : Return a deep copy of an object.
Notes¶
When
deep=True, data is copied but actual Python objects will not be copied recursively, only the reference to the object. This is in contrast to copy.deepcopy in the Standard Library, which recursively copies object data (see examples below).While
Indexobjects are copied whendeep=True, the underlying numpy array is not copied for performance reasons. SinceIndexis immutable, the underlying data can be safely shared and a copy is not needed.Since pandas is not thread safe, see the gotchas when copying in a threading environment.
Copy-on-Write protects shallow copies against accidental modifications. This means that any changes to the copied data would make a new copy of the data upon write (and vice versa). Changes made to either the original or copied variable would not be reflected in the counterpart. See Copy_on_Write for more information.
Examples¶
>>> s = pd.Series([1, 2], index=["a", "b"]) >>> s a 1 b 2 dtype: int64
>>> s_copy = s.copy(deep=True) >>> s_copy a 1 b 2 dtype: int64
Due to Copy-on-Write, shallow copies still protect data modifications. Note shallow does not get modified below.
>>> s = pd.Series([1, 2], index=["a", "b"]) >>> shallow = s.copy(deep=False) >>> s.iloc[1] = 200 >>> shallow a 1 b 2 dtype: int64
When the data has object dtype, even a deep copy does not copy the underlying Python objects. Updating a nested data object will be reflected in the deep copy.
>>> s = pd.Series([[1, 2], [3, 4]]) >>> deep = s.copy() >>> s[0][0] = 10 >>> s 0 [10, 2] 1 [3, 4] dtype: object >>> deep 0 [10, 2] 1 [3, 4] dtype: object
- head(*args, **kwargs)¶
Return the first n rows.
This function exhibits the same behavior as
df[:n], returning the firstnrows based on position. It is useful for quickly checking if your object has the right type of data in it.When
nis positive, it returns the firstnrows. Fornequal to 0, it returns an empty object. Whennis negative, it returns all rows except the last|n|rows, mirroring the behavior ofdf[:n].If
nis larger than the number of rows, this function returns all rows.Parameters¶
- nint, default 5
Number of rows to select.
Returns¶
- same type as caller
The first n rows of the caller object.
See Also¶
DataFrame.tail: Returns the last n rows.
Examples¶
>>> df = pd.DataFrame( ... { ... "animal": [ ... "alligator", ... "bee", ... "falcon", ... "lion", ... "monkey", ... "parrot", ... "shark", ... "whale", ... "zebra", ... ] ... } ... ) >>> df animal 0 alligator 1 bee 2 falcon 3 lion 4 monkey 5 parrot 6 shark 7 whale 8 zebra
Viewing the first 5 lines
>>> df.head() animal 0 alligator 1 bee 2 falcon 3 lion 4 monkey
Viewing the first n lines (three in this case)
>>> df.head(3) animal 0 alligator 1 bee 2 falcon
For negative values of n
>>> df.head(-3) animal 0 alligator 1 bee 2 falcon 3 lion 4 monkey 5 parrot
- tail(*args, **kwargs)¶
Return the last n rows.
This function returns last n rows from the object based on position. It is useful for quickly verifying data, for example, after sorting or appending rows.
For negative values of n, this function returns all rows except the first |n| rows, equivalent to
df[|n|:].If
nis larger than the number of rows, this function returns all rows.Parameters¶
- nint, default 5
Number of rows to select.
Returns¶
- type of caller
The last n rows of the caller object.
See Also¶
DataFrame.head : The first n rows of the caller object.
Examples¶
>>> df = pd.DataFrame( ... { ... "animal": [ ... "alligator", ... "bee", ... "falcon", ... "lion", ... "monkey", ... "parrot", ... "shark", ... "whale", ... "zebra", ... ] ... } ... ) >>> df animal 0 alligator 1 bee 2 falcon 3 lion 4 monkey 5 parrot 6 shark 7 whale 8 zebra
Viewing the last 5 lines
>>> df.tail() animal 4 monkey 5 parrot 6 shark 7 whale 8 zebra
Viewing the last n lines (three in this case)
>>> df.tail(3) animal 6 shark 7 whale 8 zebra
For negative values of n
>>> df.tail(-3) animal 3 lion 4 monkey 5 parrot 6 shark 7 whale 8 zebra
- drop(*args, **kwargs)¶
Return Series with specified index labels removed.
Remove elements of a Series based on specifying the index labels. When using a multi-index, labels on different levels can be removed by specifying the level.
Parameters¶
- labelssingle label or list-like
Index labels to drop.
- axis{0 or ‘index’}
Unused. Parameter needed for compatibility with DataFrame.
- indexsingle label or list-like
Redundant for application on Series, but ‘index’ can be used instead of ‘labels’.
- columnssingle label or list-like
No change is made to the Series; use ‘index’ or ‘labels’ instead.
- levelint or level name, optional
For MultiIndex, level for which the labels will be removed.
- inplacebool, default False
If True, do operation inplace and return None.
- errors{‘ignore’, ‘raise’}, default ‘raise’
If ‘ignore’, suppress error and only existing labels are dropped.
Returns¶
- Series or None
Series with specified index labels removed or None if
inplace=True.
Raises¶
- KeyError
If none of the labels are found in the index.
See Also¶
Series.reindex : Return only specified index labels of Series. Series.dropna : Return series without null values. Series.drop_duplicates : Return Series with duplicate values removed. DataFrame.drop : Drop specified labels from rows or columns.
Examples¶
>>> s = pd.Series(data=np.arange(3), index=["A", "B", "C"]) >>> s A 0 B 1 C 2 dtype: int64
Drop labels B and C
>>> s.drop(labels=["B", "C"]) A 0 dtype: int64
Drop 2nd level label in MultiIndex Series
>>> midx = pd.MultiIndex( ... levels=[["llama", "cow", "falcon"], ["speed", "weight", "length"]], ... codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]], ... ) >>> s = pd.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3], index=midx) >>> s llama speed 45.0 weight 200.0 length 1.2 cow speed 30.0 weight 250.0 length 1.5 falcon speed 320.0 weight 1.0 length 0.3 dtype: float64
>>> s.drop(labels="weight", level=1) llama speed 45.0 length 1.2 cow speed 30.0 length 1.5 falcon speed 320.0 length 0.3 dtype: float64
- reindex(*args, **kwargs)¶
Conform Series to new index with optional filling logic.
Places NA/NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and
copy=False.Parameters¶
- indexscalar, list-like, dict-like or function, optional
A scalar, list-like, dict-like or functions transformations to apply to that axis’ values.
- axis{0 or ‘index’}, default 0
The axis to rename. For Series this parameter is unused and defaults to 0.
- method{{None, ‘backfill’/’bfill’, ‘pad’/’ffill’, ‘nearest’}}
Method to use for filling holes in reindexed DataFrame. Please note: this is only applicable to DataFrames/Series with a monotonically increasing/decreasing index.
None (default): don’t fill gaps
pad / ffill: Propagate last valid observation forward to next valid.
backfill / bfill: Use next valid observation to fill gap.
nearest: Use nearest valid observations to fill gap.
- copybool, default False
This keyword is now ignored; changing its value will have no impact on the method.
Deprecated since version 3.0.0: This keyword is ignored and will be removed in pandas 4.0. Since pandas 3.0, this method always returns a new object using a lazy copy mechanism that defers copies until necessary (Copy-on-Write). See the user guide on Copy-on-Write for more details.
- levelint or name
Broadcast across a level, matching Index values on the passed MultiIndex level.
- fill_valuescalar, default np.nan
Value to use for missing values. Defaults to NaN, but can be any “compatible” value.
- limitint, default None
Maximum number of consecutive elements to forward or backward fill.
- toleranceoptional
Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations most satisfy the equation
abs(index[indexer] - target) <= tolerance.Tolerance may be a scalar value, which applies the same tolerance to all values, or list-like, which applies variable tolerance per element. List-like includes list, tuple, array, Series, and must be the same size as the index and its dtype must exactly match the index’s type.
Returns¶
- Series
Series with changed index.
See Also¶
DataFrame.set_index : Set row labels. DataFrame.reset_index : Remove row labels or move them to new columns. DataFrame.reindex_like : Change to same indices as other DataFrame.
Examples¶
DataFrame.reindexsupports two calling conventions(index=index_labels, columns=column_labels, ...)(labels, axis={{'index', 'columns'}}, ...)
We highly recommend using keyword arguments to clarify your intent.
Create a DataFrame with some fictional data.
>>> index = ["Firefox", "Chrome", "Safari", "IE10", "Konqueror"] >>> columns = ["http_status", "response_time"] >>> df = pd.DataFrame( ... [[200, 0.04], [200, 0.02], [404, 0.07], [404, 0.08], [301, 1.0]], ... columns=columns, ... index=index, ... ) >>> df http_status response_time Firefox 200 0.04 Chrome 200 0.02 Safari 404 0.07 IE10 404 0.08 Konqueror 301 1.00
Create a new index and reindex the DataFrame. By default values in the new index that do not have corresponding records in the DataFrame are assigned
NaN.>>> new_index = ["Safari", "Iceweasel", "Comodo Dragon", "IE10", "Chrome"] >>> df.reindex(new_index) http_status response_time Safari 404.0 0.07 Iceweasel NaN NaN Comodo Dragon NaN NaN IE10 404.0 0.08 Chrome 200.0 0.02
We can fill in the missing values by passing a value to the keyword
fill_value. Because the index is not monotonically increasing or decreasing, we cannot use arguments to the keywordmethodto fill theNaNvalues.>>> df.reindex(new_index, fill_value=0) http_status response_time Safari 404 0.07 Iceweasel 0 0.00 Comodo Dragon 0 0.00 IE10 404 0.08 Chrome 200 0.02
>>> df.reindex(new_index, fill_value="missing") http_status response_time Safari 404 0.07 Iceweasel missing missing Comodo Dragon missing missing IE10 404 0.08 Chrome 200 0.02
We can also reindex the columns.
>>> df.reindex(columns=["http_status", "user_agent"]) http_status user_agent Firefox 200 NaN Chrome 200 NaN Safari 404 NaN IE10 404 NaN Konqueror 301 NaN
Or we can use “axis-style” keyword arguments
>>> df.reindex(["http_status", "user_agent"], axis="columns") http_status user_agent Firefox 200 NaN Chrome 200 NaN Safari 404 NaN IE10 404 NaN Konqueror 301 NaN
To further illustrate the filling functionality in
reindex, we will create a DataFrame with a monotonically increasing index (for example, a sequence of dates).>>> date_index = pd.date_range("1/1/2010", periods=6, freq="D") >>> df2 = pd.DataFrame( ... {"prices": [100, 101, np.nan, 100, 89, 88]}, index=date_index ... ) >>> df2 prices 2010-01-01 100.0 2010-01-02 101.0 2010-01-03 NaN 2010-01-04 100.0 2010-01-05 89.0 2010-01-06 88.0
Suppose we decide to expand the DataFrame to cover a wider date range.
>>> date_index2 = pd.date_range("12/29/2009", periods=10, freq="D") >>> df2.reindex(date_index2) prices 2009-12-29 NaN 2009-12-30 NaN 2009-12-31 NaN 2010-01-01 100.0 2010-01-02 101.0 2010-01-03 NaN 2010-01-04 100.0 2010-01-05 89.0 2010-01-06 88.0 2010-01-07 NaN
The index entries that did not have a value in the original data frame (for example, ‘2009-12-29’) are by default filled with
NaN. If desired, we can fill in the missing values using one of several options.For example, to back-propagate the last valid value to fill the
NaNvalues, passbfillas an argument to themethodkeyword.>>> df2.reindex(date_index2, method="bfill") prices 2009-12-29 100.0 2009-12-30 100.0 2009-12-31 100.0 2010-01-01 100.0 2010-01-02 101.0 2010-01-03 NaN 2010-01-04 100.0 2010-01-05 89.0 2010-01-06 88.0 2010-01-07 NaN
Please note that the
NaNvalue present in the original DataFrame (at index value 2010-01-03) will not be filled by any of the value propagation schemes. This is because filling while reindexing does not look at DataFrame values, but only compares the original and desired indexes. If you do want to fill in theNaNvalues present in the original DataFrame, use thefillna()method.See the user guide for more.
- sample(*args, **kwargs)¶
Return a random sample of items from an axis of object.
You can use random_state for reproducibility.
Parameters¶
- nint, optional
Number of items from axis to return. Cannot be used with frac. Default = 1 if frac = None.
- fracfloat, optional
Fraction of axis items to return. Cannot be used with n.
- replacebool, default False
Allow or disallow sampling of the same row more than once.
- weightsstr or ndarray-like, optional
Default
Noneresults in equal probability weighting. If passed a Series, will align with target object on index. Index values in weights not found in sampled object will be ignored and index values in sampled object not in weights will be assigned weights of zero. If called on a DataFrame, will accept the name of a column when axis = 0. Unless weights are a Series, weights must be same length as axis being sampled. If weights do not sum to 1, they will be normalized to sum to 1. Missing values in the weights column will be treated as zero. Infinite values not allowed. When replace = False will not allow(n * max(weights) / sum(weights)) > 1in order to avoid biased results. See the Notes below for more details.- random_stateint, array-like, BitGenerator, np.random.RandomState, np.random.Generator, optional
If int, array-like, or BitGenerator, seed for random number generator. If np.random.RandomState or np.random.Generator, use as given. Default
Noneresults in sampling with the current state of np.random.- axis{0 or ‘index’, 1 or ‘columns’, None}, default None
Axis to sample. Accepts axis number or name. Default is stat axis for given data type. For Series this parameter is unused and defaults to None.
- ignore_indexbool, default False
If True, the resulting index will be labeled 0, 1, …, n - 1.
Returns¶
- Series or DataFrame
A new object of same type as caller containing n items randomly sampled from the caller object.
See Also¶
- DataFrameGroupBy.sample: Generates random samples from each group of a
DataFrame object.
- SeriesGroupBy.sample: Generates random samples from each group of a
Series object.
- numpy.random.choice: Generates a random sample from a given 1-D numpy
array.
Notes¶
If frac > 1, replacement should be set to True.
When replace = False will not allow
(n * max(weights) / sum(weights)) > 1, since that would cause results to be biased. E.g. sampling 2 items without replacement with weights [100, 1, 1] would yield two last items in 1/2 of cases, instead of 1/102. This is similar to specifying n=4 without replacement on a Series with 3 elements.Examples¶
>>> df = pd.DataFrame( ... { ... "num_legs": [2, 4, 8, 0], ... "num_wings": [2, 0, 0, 0], ... "num_specimen_seen": [10, 2, 1, 8], ... }, ... index=["falcon", "dog", "spider", "fish"], ... ) >>> df num_legs num_wings num_specimen_seen falcon 2 2 10 dog 4 0 2 spider 8 0 1 fish 0 0 8
Extract 3 random elements from the
Seriesdf['num_legs']: Note that we use random_state to ensure the reproducibility of the examples.>>> df["num_legs"].sample(n=3, random_state=1) fish 0 spider 8 falcon 2 Name: num_legs, dtype: int64
A random 50% sample of the
DataFramewith replacement:>>> df.sample(frac=0.5, replace=True, random_state=1) num_legs num_wings num_specimen_seen dog 4 0 2 fish 0 0 8
An upsample sample of the
DataFramewith replacement: Note that replace parameter has to be True for frac parameter > 1.>>> df.sample(frac=2, replace=True, random_state=1) num_legs num_wings num_specimen_seen dog 4 0 2 fish 0 0 8 falcon 2 2 10 falcon 2 2 10 fish 0 0 8 dog 4 0 2 fish 0 0 8 dog 4 0 2
Using a DataFrame column as weights. Rows with larger value in the num_specimen_seen column are more likely to be sampled.
>>> df.sample(n=2, weights="num_specimen_seen", random_state=1) num_legs num_wings num_specimen_seen falcon 2 2 10 fish 0 0 8
- rename(*args, **kwargs)¶
Alter Series index labels or name.
Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don’t throw an error.
Alternatively, change
Series.namewith a scalar value.See the user guide for more.
Parameters¶
- indexscalar, hashable sequence, dict-like or function optional
Functions or dict-like are transformations to apply to the index. Scalar or hashable sequence-like will alter the
Series.nameattribute.- axis{0 or ‘index’}
Unused. Parameter needed for compatibility with DataFrame.
- copybool, default False
This keyword is now ignored; changing its value will have no impact on the method.
Deprecated since version 3.0.0: This keyword is ignored and will be removed in pandas 4.0. Since pandas 3.0, this method always returns a new object using a lazy copy mechanism that defers copies until necessary (Copy-on-Write). See the user guide on Copy-on-Write for more details.
- inplacebool, default False
Whether to return a new Series. If True the value of copy is ignored.
- levelint or level name, default None
In case of MultiIndex, only rename labels in the specified level.
- errors{‘ignore’, ‘raise’}, default ‘ignore’
If ‘raise’, raise KeyError when a dict-like mapper or index contains labels that are not present in the index being transformed. If ‘ignore’, existing keys will be renamed and extra keys will be ignored.
Returns¶
- Series
A shallow copy with index labels or name altered, or the same object if
inplace=Trueand index is not a dict or callable else None.
See Also¶
DataFrame.rename : Corresponding DataFrame method. Series.rename_axis : Set the name of the axis.
Examples¶
>>> s = pd.Series([1, 2, 3]) >>> s 0 1 1 2 2 3 dtype: int64 >>> s.rename("my_name") # scalar, changes Series.name 0 1 1 2 2 3 Name: my_name, dtype: int64 >>> s.rename(lambda x: x**2) # function, changes labels 0 1 1 2 4 3 dtype: int64 >>> s.rename({1: 3, 2: 5}) # mapping, changes labels 0 1 3 2 5 3 dtype: int64
- rename_axis(*args, **kwargs)¶
Set the name of the axis for the index.
Parameters¶
- mapperscalar, list-like, optional
Value to set the axis name attribute.
Use either
mapperandaxisto specify the axis to target withmapper, orindex.- indexscalar, list-like, dict-like or function, optional
A scalar, list-like, dict-like or functions transformations to apply to that axis’ values.
- axis{0 or ‘index’}, default 0
The axis to rename. For Series this parameter is unused and defaults to 0.
- copybool, default False
This keyword is now ignored; changing its value will have no impact on the method.
Deprecated since version 3.0.0: This keyword is ignored and will be removed in pandas 4.0. Since pandas 3.0, this method always returns a new object using a lazy copy mechanism that defers copies until necessary (Copy-on-Write). See the user guide on Copy-on-Write for more details.
- inplacebool, default False
Modifies the object directly, instead of creating a new Series or DataFrame.
Returns¶
- Series, or None
The same type as the caller or None if
inplace=True.
See Also¶
Series.rename : Alter Series index labels or name. DataFrame.rename : Alter DataFrame index labels or name. Index.rename : Set new names on index.
Examples¶
>>> s = pd.Series(["dog", "cat", "monkey"]) >>> s 0 dog 1 cat 2 monkey dtype: str >>> s.rename_axis("animal") animal 0 dog 1 cat 2 monkey dtype: str
- set_axis(*args, **kwargs)¶
Assign desired index to given axis.
Deprecated since version 3.0.0: This keyword is ignored and will be removed in pandas 4.0. Since pandas 3.0, this method always returns a new object using a lazy copy mechanism that defers copies until necessary (Copy-on-Write). See the user guide on Copy-on-Write for more details.
Indexes for row labels can be changed by assigning a list-like or Index.
Parameters¶
- labelslist-like or Index
The values for the new index.
- axis{0 or ‘index’}, default 0
The axis to update. The value 0 identifies the rows. For Series this parameter is unused and defaults to 0.
- copybool, default False
This keyword is now ignored; changing its value will have no impact on the method.
Returns¶
- Series
A shallow copy of the object with axis altered to the given index.
See Also¶
Series.rename_axis : Alter the name of the index.
Examples¶
>>> s = pd.Series([1, 2, 3]) >>> s 0 1 1 2 2 3 dtype: int64 >>> s.set_axis(["a", "b", "c"], axis=0) a 1 b 2 c 3 dtype: int64
- apply(func, convert_dtype: bool | None = None, args=(), **kwargs)¶
Invoke function on values of Series.
Can be ufunc (a NumPy function that applies to the entire Series) or a Python function that only works on single values.
Parameters¶
- funcfunction
Python function or NumPy ufunc to apply.
- argstuple
Positional arguments passed to func after the series value.
- by_rowFalse or “compat”, default “compat”
If
"compat"and func is a callable, func will be passed each element of the Series, likeSeries.map. If func is a list or dict of callables, will first try to translate each func into pandas methods. If that doesn’t work, will try call to apply again withby_row="compat"and if that fails, will call apply again withby_row=False(backward compatible). If False, the func will be passed the whole Series at once.by_rowhas no effect whenfuncis a string.Added in version 2.1.0.
- **kwargs
Additional keyword arguments passed to func.
Returns¶
- Series or DataFrame
If func returns a Series object the result will be a DataFrame.
See Also¶
Series.map: For element-wise operations. Series.agg: Only perform aggregating type operations. Series.transform: Only perform transforming type operations.
Notes¶
Functions that mutate the passed object can produce unexpected behavior or errors and are not supported. See gotchas.udf-mutation for more details.
Examples¶
Create a series with typical summer temperatures for each city.
>>> s = pd.Series([20, 21, 12], index=["London", "New York", "Helsinki"]) >>> s London 20 New York 21 Helsinki 12 dtype: int64
Square the values by defining a function and passing it as an argument to
apply().>>> def square(x): ... return x**2 >>> s.apply(square) London 400 New York 441 Helsinki 144 dtype: int64
Square the values by passing an anonymous function as an argument to
apply().>>> s.apply(lambda x: x**2) London 400 New York 441 Helsinki 144 dtype: int64
Define a custom function that needs additional positional arguments and pass these additional arguments using the
argskeyword.>>> def subtract_custom_value(x, custom_value): ... return x - custom_value
>>> s.apply(subtract_custom_value, args=(5,)) London 15 New York 16 Helsinki 7 dtype: int64
Define a custom function that takes keyword arguments and pass these arguments to
apply.>>> def add_custom_values(x, **kwargs): ... for month in kwargs: ... x += kwargs[month] ... return x
>>> s.apply(add_custom_values, june=30, july=20, august=25) London 95 New York 96 Helsinki 87 dtype: int64
Use a function from the Numpy library.
>>> s.apply(np.log) London 2.995732 New York 3.044522 Helsinki 2.484907 dtype: float64
- isna() pandas.Series¶
Detect missing values.
Historically, NA values in a GeoSeries could be represented by empty geometric objects, in addition to standard representations such as None and np.nan. This behaviour is changed in version 0.6.0, and now only actual missing values return True. To detect empty geometries, use
GeoSeries.is_emptyinstead.Returns¶
A boolean pandas Series of the same size as the GeoSeries, True where a value is NA.
Examples¶
>>> from shapely.geometry import Polygon >>> s = geopandas.GeoSeries( ... [Polygon([(0, 0), (1, 1), (0, 1)]), None, Polygon([])] ... ) >>> s 0 POLYGON ((0 0, 1 1, 0 1, 0 0)) 1 None 2 POLYGON EMPTY dtype: geometry
>>> s.isna() 0 False 1 True 2 False dtype: bool
See Also¶
GeoSeries.notna : inverse of isna GeoSeries.is_empty : detect empty geometries
- isnull() pandas.Series¶
Alias for isna method. See isna for more detail.
- notna() pandas.Series¶
Detect non-missing values.
Historically, NA values in a GeoSeries could be represented by empty geometric objects, in addition to standard representations such as None and np.nan. This behaviour is changed in version 0.6.0, and now only actual missing values return False. To detect empty geometries, use
~GeoSeries.is_emptyinstead.Returns¶
A boolean pandas Series of the same size as the GeoSeries, False where a value is NA.
Examples¶
>>> from shapely.geometry import Polygon >>> s = geopandas.GeoSeries( ... [Polygon([(0, 0), (1, 1), (0, 1)]), None, Polygon([])] ... ) >>> s 0 POLYGON ((0 0, 1 1, 0 1, 0 0)) 1 None 2 POLYGON EMPTY dtype: geometry
>>> s.notna() 0 True 1 False 2 True dtype: bool
See Also¶
GeoSeries.isna : inverse of notna GeoSeries.is_empty : detect empty geometries
- notnull() pandas.Series¶
Alias for notna method. See notna for more detail.
- fillna(value=None, inplace: bool = False, limit=None, **kwargs)¶
Fill NA values with geometry (or geometries).
Parameters¶
- valueshapely geometry or GeoSeries, default None
If None is passed, NA values will be filled with GEOMETRYCOLLECTION EMPTY. If a shapely geometry object is passed, it will be used to fill all missing values. If a
GeoSeriesorGeometryArrayare passed, missing values will be filled based on the corresponding index locations. If pd.NA or np.nan are passed, values will be filled withNone(not GEOMETRYCOLLECTION EMPTY).- limitint, default None
This is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None.
Returns¶
GeoSeries
Examples¶
>>> from shapely.geometry import Polygon >>> s = geopandas.GeoSeries( ... [ ... Polygon([(0, 0), (1, 1), (0, 1)]), ... None, ... Polygon([(0, 0), (-1, 1), (0, -1)]), ... ] ... ) >>> s 0 POLYGON ((0 0, 1 1, 0 1, 0 0)) 1 None 2 POLYGON ((0 0, -1 1, 0 -1, 0 0)) dtype: geometry
Filled with an empty polygon.
>>> s.fillna() 0 POLYGON ((0 0, 1 1, 0 1, 0 0)) 1 GEOMETRYCOLLECTION EMPTY 2 POLYGON ((0 0, -1 1, 0 -1, 0 0)) dtype: geometry
Filled with a specific polygon.
>>> s.fillna(Polygon([(0, 1), (2, 1), (1, 2)])) 0 POLYGON ((0 0, 1 1, 0 1, 0 0)) 1 POLYGON ((0 1, 2 1, 1 2, 0 1)) 2 POLYGON ((0 0, -1 1, 0 -1, 0 0)) dtype: geometry
Filled with another GeoSeries.
>>> from shapely.geometry import Point >>> s_fill = geopandas.GeoSeries( ... [ ... Point(0, 0), ... Point(1, 1), ... Point(2, 2), ... ] ... ) >>> s.fillna(s_fill) 0 POLYGON ((0 0, 1 1, 0 1, 0 0)) 1 POINT (1 1) 2 POLYGON ((0 0, -1 1, 0 -1, 0 0)) dtype: geometry
See Also¶
GeoSeries.isna : detect missing values
- plot(*args, **kwargs)¶
- explore(*args, **kwargs)¶
Explore with an interactive map based on folium/leaflet.js.
- explode(ignore_index=False, index_parts=False) GeoSeries¶
Explode multi-part geometries into multiple single geometries.
Single rows can become multiple rows. This is analogous to PostGIS’s ST_Dump(). The ‘path’ index is the second level of the returned MultiIndex
Parameters¶
- ignore_indexbool, default False
If True, the resulting index will be labelled 0, 1, …, n - 1, ignoring index_parts.
- index_partsboolean, default False
If True, the resulting index will be a multi-index (original index with an additional level indicating the multiple geometries: a new zero-based index for each single part geometry per multi-part geometry).
Returns¶
A GeoSeries with a MultiIndex. The levels of the MultiIndex are the original index and a zero-based integer index that counts the number of single geometries within a multi-part geometry.
Examples¶
>>> from shapely.geometry import MultiPoint >>> s = geopandas.GeoSeries( ... [MultiPoint([(0, 0), (1, 1)]), MultiPoint([(2, 2), (3, 3), (4, 4)])] ... ) >>> s 0 MULTIPOINT ((0 0), (1 1)) 1 MULTIPOINT ((2 2), (3 3), (4 4)) dtype: geometry
>>> s.explode(index_parts=True) 0 0 POINT (0 0) 1 POINT (1 1) 1 0 POINT (2 2) 1 POINT (3 3) 2 POINT (4 4) dtype: geometry
See Also¶
GeoDataFrame.explode
- set_crs(crs: Any | None = None, epsg: int | None = None, inplace: bool = False, allow_override: bool = False)¶
Set the Coordinate Reference System (CRS) of a
GeoSeries.Pass
Noneto remove CRS from theGeoSeries.Notes¶
The underlying geometries are not transformed to this CRS. To transform the geometries to a new CRS, use the
to_crsmethod.Parameters¶
- crspyproj.CRS | None, optional
The value can be anything accepted by
pyproj.CRS.from_user_input(), such as an authority string (eg “EPSG:4326”) or a WKT string.- epsgint, optional if crs is specified
EPSG code specifying the projection.
- inplacebool, default False
If True, the CRS of the GeoSeries will be changed in place (while still returning the result) instead of making a copy of the GeoSeries.
- allow_overridebool, default False
If the the GeoSeries already has a CRS, allow to replace the existing CRS, even when both are not equal.
Returns¶
GeoSeries
Examples¶
>>> from shapely.geometry import Point >>> s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)]) >>> s 0 POINT (1 1) 1 POINT (2 2) 2 POINT (3 3) dtype: geometry
Setting CRS to a GeoSeries without one:
>>> s.crs is None True
>>> s = s.set_crs('epsg:3857') >>> s.crs <Projected CRS: EPSG:3857> Name: WGS 84 / Pseudo-Mercator Axis Info [cartesian]: - X[east]: Easting (metre) - Y[north]: Northing (metre) Area of Use: - name: World - 85°S to 85°N - bounds: (-180.0, -85.06, 180.0, 85.06) Coordinate Operation: - name: Popular Visualisation Pseudo-Mercator - method: Popular Visualisation Pseudo Mercator Datum: World Geodetic System 1984 - Ellipsoid: WGS 84 - Prime Meridian: Greenwich
Overriding existing CRS:
>>> s = s.set_crs(4326, allow_override=True)
Without
allow_override=True,set_crsreturns an error if you try to override CRS.See Also¶
GeoSeries.to_crs : re-project to another CRS
- to_crs(crs: Any | None = None, epsg: int | None = None) GeoSeries¶
Return a
GeoSerieswith all geometries transformed to a new coordinate reference system.Transform all geometries in a GeoSeries to a different coordinate reference system. The
crsattribute on the current GeoSeries must be set. Eithercrsorepsgmay be specified for output.This method will transform all points in all objects. It has no notion of projecting entire geometries. All segments joining points are assumed to be lines in the current projection, not geodesics. Objects crossing the dateline (or other projection boundary) will have undesirable behavior.
Parameters¶
- crspyproj.CRS, optional if epsg is specified
The value can be anything accepted by
pyproj.CRS.from_user_input(), such as an authority string (eg “EPSG:4326”) or a WKT string.- epsgint, optional if crs is specified
EPSG code specifying output projection.
Returns¶
GeoSeries
Examples¶
>>> from shapely.geometry import Point >>> s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)], crs=4326) >>> s 0 POINT (1 1) 1 POINT (2 2) 2 POINT (3 3) dtype: geometry >>> s.crs <Geographic 2D CRS: EPSG:4326> Name: WGS 84 Axis Info [ellipsoidal]: - Lat[north]: Geodetic latitude (degree) - Lon[east]: Geodetic longitude (degree) Area of Use: - name: World - bounds: (-180.0, -90.0, 180.0, 90.0) Datum: World Geodetic System 1984 - Ellipsoid: WGS 84 - Prime Meridian: Greenwich
>>> s = s.to_crs(3857) >>> s 0 POINT (111319.491 111325.143) 1 POINT (222638.982 222684.209) 2 POINT (333958.472 334111.171) dtype: geometry >>> s.crs <Projected CRS: EPSG:3857> Name: WGS 84 / Pseudo-Mercator Axis Info [cartesian]: - X[east]: Easting (metre) - Y[north]: Northing (metre) Area of Use: - name: World - 85°S to 85°N - bounds: (-180.0, -85.06, 180.0, 85.06) Coordinate Operation: - name: Popular Visualisation Pseudo-Mercator - method: Popular Visualisation Pseudo Mercator Datum: World Geodetic System 1984 - Ellipsoid: WGS 84 - Prime Meridian: Greenwich
See Also¶
GeoSeries.set_crs : assign CRS
- estimate_utm_crs(datum_name: str = 'WGS 84')¶
Return the estimated UTM CRS based on the bounds of the dataset.
Added in version 0.9.
Parameters¶
- datum_namestr, optional
The name of the datum to use in the query. Default is WGS 84.
Returns¶
pyproj.CRS
Examples¶
>>> import geodatasets >>> df = geopandas.read_file( ... geodatasets.get_path("geoda.chicago_health") ... ) >>> df.geometry.estimate_utm_crs() <Derived Projected CRS: EPSG:32616> Name: WGS 84 / UTM zone 16N Axis Info [cartesian]: - E[east]: Easting (metre) - N[north]: Northing (metre) Area of Use: - name: Between 90°W and 84°W, northern hemisphere between equator and 84°N, ... - bounds: (-90.0, 0.0, -84.0, 84.0) Coordinate Operation: - name: UTM zone 16N - method: Transverse Mercator Datum: World Geodetic System 1984 ensemble - Ellipsoid: WGS 84 - Prime Meridian: Greenwich
- to_json(show_bbox: bool = True, drop_id: bool = False, to_wgs84: bool = False, **kwargs) str¶
Return a GeoJSON string representation of the GeoSeries.
Parameters¶
- show_bboxbool, optional, default: True
Include bbox (bounds) in the geojson
- drop_idbool, default: False
Whether to retain the index of the GeoSeries as the id property in the generated GeoJSON. Default is False, but may want True if the index is just arbitrary row numbers.
- to_wgs84: bool, optional, default: False
If the CRS is set on the active geometry column it is exported as WGS84 (EPSG:4326) to meet the 2016 GeoJSON specification. Set to True to force re-projection and set to False to ignore CRS. False by default.
kwargs that will be passed to json.dumps().
Returns¶
JSON string
Examples¶
>>> from shapely.geometry import Point >>> s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)]) >>> s 0 POINT (1 1) 1 POINT (2 2) 2 POINT (3 3) dtype: geometry
>>> s.to_json() '{"type": "FeatureCollection", "features": [{"id": "0", "type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [1.0, 1.0]}, "bbox": [1.0, 1.0, 1.0, 1.0]}, {"id": "1", "type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [2.0, 2.0]}, "bbox": [2.0, 2.0, 2.0, 2.0]}, {"id": "2", "type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [3.0, 3.0]}, "bbox": [3.0, 3.0, 3.0, 3.0]}], "bbox": [1.0, 1.0, 3.0, 3.0]}'
See Also¶
GeoSeries.to_file : write GeoSeries to file
- to_wkb(hex: bool = False, **kwargs) pandas.Series¶
Convert GeoSeries geometries to WKB.
Parameters¶
- hexbool
If true, export the WKB as a hexadecimal string. The default is to return a binary bytes object.
- kwargs
Additional keyword args will be passed to
shapely.to_wkb().
Returns¶
- Series
WKB representations of the geometries
See Also¶
GeoSeries.to_wkt
Examples¶
>>> from shapely.geometry import Point, Polygon >>> s = geopandas.GeoSeries( ... [ ... Point(0, 0), ... Polygon(), ... Polygon([(0, 0), (1, 1), (1, 0)]), ... None, ... ] ... )
>>> s.to_wkb() 0 b'\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00... 1 b'\x01\x03\x00\x00\x00\x00\x00\x00\x00' 2 b'\x01\x03\x00\x00\x00\x01\x00\x00\x00\x04\x00... 3 None dtype: object
>>> s.to_wkb(hex=True) 0 010100000000000000000000000000000000000000 1 010300000000000000 2 0103000000010000000400000000000000000000000000... 3 NaN dtype: str
- to_wkt(**kwargs) pandas.Series¶
Convert GeoSeries geometries to WKT.
Parameters¶
- kwargs
Keyword args will be passed to
shapely.to_wkt().
Returns¶
- Series
WKT representations of the geometries
Examples¶
>>> from shapely.geometry import Point >>> s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)]) >>> s 0 POINT (1 1) 1 POINT (2 2) 2 POINT (3 3) dtype: geometry
>>> s.to_wkt() 0 POINT (1 1) 1 POINT (2 2) 2 POINT (3 3) dtype: str
See Also¶
GeoSeries.to_wkb
- to_arrow(geometry_encoding='WKB', interleaved=True, include_z=None)¶
Encode a GeoSeries to GeoArrow format.
See https://geoarrow.org/ for details on the GeoArrow specification.
This functions returns a generic Arrow array object implementing the Arrow PyCapsule Protocol (i.e. having an
__arrow_c_array__method). This object can then be consumed by your Arrow implementation of choice that supports this protocol.Added in version 1.0.
Parameters¶
- geometry_encoding{‘WKB’, ‘geoarrow’ }, default ‘WKB’
The GeoArrow encoding to use for the data conversion.
- interleavedbool, default True
Only relevant for ‘geoarrow’ encoding. If True, the geometries’ coordinates are interleaved in a single fixed size list array. If False, the coordinates are stored as separate arrays in a struct type.
- include_zbool, default None
Only relevant for ‘geoarrow’ encoding (for WKB, the dimensionality of the individual geometries is preserved). If False, return 2D geometries. If True, include the third dimension in the output (if a geometry has no third dimension, the z-coordinates will be NaN). By default, will infer the dimensionality from the input geometries. Note that this inference can be unreliable with empty geometries (for a guaranteed result, it is recommended to specify the keyword).
Returns¶
- GeoArrowArray
A generic Arrow array object with geometry data encoded to GeoArrow.
Examples¶
>>> from shapely.geometry import Point >>> gser = geopandas.GeoSeries([Point(1, 2), Point(2, 1)]) >>> gser 0 POINT (1 2) 1 POINT (2 1) dtype: geometry
>>> arrow_array = gser.to_arrow() >>> arrow_array <geopandas.io._geoarrow.GeoArrowArray object at ...>
The returned array object needs to be consumed by a library implementing the Arrow PyCapsule Protocol. For example, wrapping the data as a pyarrow.Array (requires pyarrow >= 14.0):
>>> import pyarrow as pa >>> array = pa.array(arrow_array) >>> array GeometryExtensionArray:WkbType(geoarrow.wkb)[2] <POINT (1 2)> <POINT (2 1)>
- clip(mask, keep_geom_type: bool = False, sort=False) GeoSeries¶
Clip points, lines, or polygon geometries to the mask extent.
Both layers must be in the same Coordinate Reference System (CRS). The GeoSeries will be clipped to the full extent of the mask object.
If there are multiple polygons in mask, data from the GeoSeries will be clipped to the total boundary of all polygons in mask.
Parameters¶
- maskGeoDataFrame, GeoSeries, (Multi)Polygon, list-like
Polygon vector layer used to clip gdf. The mask’s geometry is dissolved into one geometric feature and intersected with GeoSeries. If the mask is list-like with four elements
(minx, miny, maxx, maxy),clipwill use a faster rectangle clipping (clip_by_rect()), possibly leading to slightly different results.- keep_geom_typeboolean, default False
If True, return only geometries of original type in case of intersection resulting in multiple geometry types or GeometryCollections. If False, return all resulting geometries (potentially mixed-types).
- sortboolean, default False
If True, the order of rows in the clipped GeoSeries will be preserved at small performance cost. If False the order of rows in the clipped GeoSeries will be random.
Returns¶
- GeoSeries
Vector data (points, lines, polygons) from gdf clipped to polygon boundary from mask.
See Also¶
clip : top-level function for clip
Examples¶
Clip points (grocery stores) with polygons (the Near West Side community):
>>> import geodatasets >>> chicago = geopandas.read_file( ... geodatasets.get_path("geoda.chicago_health") ... ) >>> near_west_side = chicago[chicago["community"] == "NEAR WEST SIDE"] >>> groceries = geopandas.read_file( ... geodatasets.get_path("geoda.groceries") ... ).to_crs(chicago.crs) >>> groceries.shape (148, 8)
>>> nws_groceries = groceries.geometry.clip(near_west_side) >>> nws_groceries.shape (7,)