doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
pandas.Series.dt.day_of_week Series.dt.day_of_week The day of the week with Monday=0, Sunday=6. Return the day of the week. It is assumed the week starts on Monday, which is denoted by 0 and ends on Sunday which is denoted by 6. This method is available on both Series with datetime values (using the dt accessor) or DatetimeIndex. Returns Series or Index Containing integers indicating the day number. See also Series.dt.dayofweek Alias. Series.dt.weekday Alias. Series.dt.day_name Returns the name of the day of the week. Examples >>> s = pd.date_range('2016-12-31', '2017-01-08', freq='D').to_series() >>> s.dt.dayofweek 2016-12-31 5 2017-01-01 6 2017-01-02 0 2017-01-03 1 2017-01-04 2 2017-01-05 3 2017-01-06 4 2017-01-07 5 2017-01-08 6 Freq: D, dtype: int64
pandas.reference.api.pandas.series.dt.day_of_week
pandas.Series.dt.day_of_year Series.dt.day_of_year The ordinal day of the year.
pandas.reference.api.pandas.series.dt.day_of_year
pandas.Series.dt.dayofweek Series.dt.dayofweek The day of the week with Monday=0, Sunday=6. Return the day of the week. It is assumed the week starts on Monday, which is denoted by 0 and ends on Sunday which is denoted by 6. This method is available on both Series with datetime values (using the dt accessor) or DatetimeIndex. Returns Series or Index Containing integers indicating the day number. See also Series.dt.dayofweek Alias. Series.dt.weekday Alias. Series.dt.day_name Returns the name of the day of the week. Examples >>> s = pd.date_range('2016-12-31', '2017-01-08', freq='D').to_series() >>> s.dt.dayofweek 2016-12-31 5 2017-01-01 6 2017-01-02 0 2017-01-03 1 2017-01-04 2 2017-01-05 3 2017-01-06 4 2017-01-07 5 2017-01-08 6 Freq: D, dtype: int64
pandas.reference.api.pandas.series.dt.dayofweek
pandas.Series.dt.dayofyear Series.dt.dayofyear The ordinal day of the year.
pandas.reference.api.pandas.series.dt.dayofyear
pandas.Series.dt.days Series.dt.days Number of days for each element.
pandas.reference.api.pandas.series.dt.days
pandas.Series.dt.days_in_month Series.dt.days_in_month The number of days in the month.
pandas.reference.api.pandas.series.dt.days_in_month
pandas.Series.dt.daysinmonth Series.dt.daysinmonth The number of days in the month.
pandas.reference.api.pandas.series.dt.daysinmonth
pandas.Series.dt.end_time Series.dt.end_time
pandas.reference.api.pandas.series.dt.end_time
pandas.Series.dt.floor Series.dt.floor(*args, **kwargs)[source] Perform floor operation on the data to the specified freq. Parameters freq:str or Offset The frequency level to floor the index to. Must be a fixed frequency like ‘S’ (second) not ‘ME’ (month end). See frequency aliases for a list of possible freq values. ambiguous:‘infer’, bool-ndarray, ‘NaT’, default ‘raise’ Only relevant for DatetimeIndex: ‘infer’ will attempt to infer fall dst-transition hours based on order bool-ndarray where True signifies a DST time, False designates a non-DST time (note that this flag is only applicable for ambiguous times) ‘NaT’ will return NaT where there are ambiguous times ‘raise’ will raise an AmbiguousTimeError if there are ambiguous times. nonexistent:‘shift_forward’, ‘shift_backward’, ‘NaT’, timedelta, default ‘raise’ A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST. ‘shift_forward’ will shift the nonexistent time forward to the closest existing time ‘shift_backward’ will shift the nonexistent time backward to the closest existing time ‘NaT’ will return NaT where there are nonexistent times timedelta objects will shift nonexistent times by the timedelta ‘raise’ will raise an NonExistentTimeError if there are nonexistent times. Returns DatetimeIndex, TimedeltaIndex, or Series Index of the same type for a DatetimeIndex or TimedeltaIndex, or a Series with the same index for a Series. Raises ValueError if the freq cannot be converted. Notes If the timestamps have a timezone, flooring will take place relative to the local (“wall”) time and re-localized to the same timezone. When flooring near daylight savings time, use nonexistent and ambiguous to control the re-localization behavior. Examples DatetimeIndex >>> rng = pd.date_range('1/1/2018 11:59:00', periods=3, freq='min') >>> rng DatetimeIndex(['2018-01-01 11:59:00', '2018-01-01 12:00:00', '2018-01-01 12:01:00'], dtype='datetime64[ns]', freq='T') >>> rng.floor('H') DatetimeIndex(['2018-01-01 11:00:00', '2018-01-01 12:00:00', '2018-01-01 12:00:00'], dtype='datetime64[ns]', freq=None) Series >>> pd.Series(rng).dt.floor("H") 0 2018-01-01 11:00:00 1 2018-01-01 12:00:00 2 2018-01-01 12:00:00 dtype: datetime64[ns] When rounding near a daylight savings time transition, use ambiguous or nonexistent to control how the timestamp should be re-localized. >>> rng_tz = pd.DatetimeIndex(["2021-10-31 03:30:00"], tz="Europe/Amsterdam") >>> rng_tz.floor("2H", ambiguous=False) DatetimeIndex(['2021-10-31 02:00:00+01:00'], dtype='datetime64[ns, Europe/Amsterdam]', freq=None) >>> rng_tz.floor("2H", ambiguous=True) DatetimeIndex(['2021-10-31 02:00:00+02:00'], dtype='datetime64[ns, Europe/Amsterdam]', freq=None)
pandas.reference.api.pandas.series.dt.floor
pandas.Series.dt.freq Series.dt.freq
pandas.reference.api.pandas.series.dt.freq
pandas.Series.dt.hour Series.dt.hour The hours of the datetime. Examples >>> datetime_series = pd.Series( ... pd.date_range("2000-01-01", periods=3, freq="h") ... ) >>> datetime_series 0 2000-01-01 00:00:00 1 2000-01-01 01:00:00 2 2000-01-01 02:00:00 dtype: datetime64[ns] >>> datetime_series.dt.hour 0 0 1 1 2 2 dtype: int64
pandas.reference.api.pandas.series.dt.hour
pandas.Series.dt.is_leap_year Series.dt.is_leap_year Boolean indicator if the date belongs to a leap year. A leap year is a year, which has 366 days (instead of 365) including 29th of February as an intercalary day. Leap years are years which are multiples of four with the exception of years divisible by 100 but not by 400. Returns Series or ndarray Booleans indicating if dates belong to a leap year. Examples This method is available on Series with datetime values under the .dt accessor, and directly on DatetimeIndex. >>> idx = pd.date_range("2012-01-01", "2015-01-01", freq="Y") >>> idx DatetimeIndex(['2012-12-31', '2013-12-31', '2014-12-31'], dtype='datetime64[ns]', freq='A-DEC') >>> idx.is_leap_year array([ True, False, False]) >>> dates_series = pd.Series(idx) >>> dates_series 0 2012-12-31 1 2013-12-31 2 2014-12-31 dtype: datetime64[ns] >>> dates_series.dt.is_leap_year 0 True 1 False 2 False dtype: bool
pandas.reference.api.pandas.series.dt.is_leap_year
pandas.Series.dt.is_month_end Series.dt.is_month_end Indicates whether the date is the last day of the month. Returns Series or array For Series, returns a Series with boolean values. For DatetimeIndex, returns a boolean array. See also is_month_start Return a boolean indicating whether the date is the first day of the month. is_month_end Return a boolean indicating whether the date is the last day of the month. Examples This method is available on Series with datetime values under the .dt accessor, and directly on DatetimeIndex. >>> s = pd.Series(pd.date_range("2018-02-27", periods=3)) >>> s 0 2018-02-27 1 2018-02-28 2 2018-03-01 dtype: datetime64[ns] >>> s.dt.is_month_start 0 False 1 False 2 True dtype: bool >>> s.dt.is_month_end 0 False 1 True 2 False dtype: bool >>> idx = pd.date_range("2018-02-27", periods=3) >>> idx.is_month_start array([False, False, True]) >>> idx.is_month_end array([False, True, False])
pandas.reference.api.pandas.series.dt.is_month_end
pandas.Series.dt.is_month_start Series.dt.is_month_start Indicates whether the date is the first day of the month. Returns Series or array For Series, returns a Series with boolean values. For DatetimeIndex, returns a boolean array. See also is_month_start Return a boolean indicating whether the date is the first day of the month. is_month_end Return a boolean indicating whether the date is the last day of the month. Examples This method is available on Series with datetime values under the .dt accessor, and directly on DatetimeIndex. >>> s = pd.Series(pd.date_range("2018-02-27", periods=3)) >>> s 0 2018-02-27 1 2018-02-28 2 2018-03-01 dtype: datetime64[ns] >>> s.dt.is_month_start 0 False 1 False 2 True dtype: bool >>> s.dt.is_month_end 0 False 1 True 2 False dtype: bool >>> idx = pd.date_range("2018-02-27", periods=3) >>> idx.is_month_start array([False, False, True]) >>> idx.is_month_end array([False, True, False])
pandas.reference.api.pandas.series.dt.is_month_start
pandas.Series.dt.is_quarter_end Series.dt.is_quarter_end Indicator for whether the date is the last day of a quarter. Returns is_quarter_end:Series or DatetimeIndex The same type as the original data with boolean values. Series will have the same name and index. DatetimeIndex will have the same name. See also quarter Return the quarter of the date. is_quarter_start Similar property indicating the quarter start. Examples This method is available on Series with datetime values under the .dt accessor, and directly on DatetimeIndex. >>> df = pd.DataFrame({'dates': pd.date_range("2017-03-30", ... periods=4)}) >>> df.assign(quarter=df.dates.dt.quarter, ... is_quarter_end=df.dates.dt.is_quarter_end) dates quarter is_quarter_end 0 2017-03-30 1 False 1 2017-03-31 1 True 2 2017-04-01 2 False 3 2017-04-02 2 False >>> idx = pd.date_range('2017-03-30', periods=4) >>> idx DatetimeIndex(['2017-03-30', '2017-03-31', '2017-04-01', '2017-04-02'], dtype='datetime64[ns]', freq='D') >>> idx.is_quarter_end array([False, True, False, False])
pandas.reference.api.pandas.series.dt.is_quarter_end
pandas.Series.dt.is_quarter_start Series.dt.is_quarter_start Indicator for whether the date is the first day of a quarter. Returns is_quarter_start:Series or DatetimeIndex The same type as the original data with boolean values. Series will have the same name and index. DatetimeIndex will have the same name. See also quarter Return the quarter of the date. is_quarter_end Similar property for indicating the quarter start. Examples This method is available on Series with datetime values under the .dt accessor, and directly on DatetimeIndex. >>> df = pd.DataFrame({'dates': pd.date_range("2017-03-30", ... periods=4)}) >>> df.assign(quarter=df.dates.dt.quarter, ... is_quarter_start=df.dates.dt.is_quarter_start) dates quarter is_quarter_start 0 2017-03-30 1 False 1 2017-03-31 1 False 2 2017-04-01 2 True 3 2017-04-02 2 False >>> idx = pd.date_range('2017-03-30', periods=4) >>> idx DatetimeIndex(['2017-03-30', '2017-03-31', '2017-04-01', '2017-04-02'], dtype='datetime64[ns]', freq='D') >>> idx.is_quarter_start array([False, False, True, False])
pandas.reference.api.pandas.series.dt.is_quarter_start
pandas.Series.dt.is_year_end Series.dt.is_year_end Indicate whether the date is the last day of the year. Returns Series or DatetimeIndex The same type as the original data with boolean values. Series will have the same name and index. DatetimeIndex will have the same name. See also is_year_start Similar property indicating the start of the year. Examples This method is available on Series with datetime values under the .dt accessor, and directly on DatetimeIndex. >>> dates = pd.Series(pd.date_range("2017-12-30", periods=3)) >>> dates 0 2017-12-30 1 2017-12-31 2 2018-01-01 dtype: datetime64[ns] >>> dates.dt.is_year_end 0 False 1 True 2 False dtype: bool >>> idx = pd.date_range("2017-12-30", periods=3) >>> idx DatetimeIndex(['2017-12-30', '2017-12-31', '2018-01-01'], dtype='datetime64[ns]', freq='D') >>> idx.is_year_end array([False, True, False])
pandas.reference.api.pandas.series.dt.is_year_end
pandas.Series.dt.is_year_start Series.dt.is_year_start Indicate whether the date is the first day of a year. Returns Series or DatetimeIndex The same type as the original data with boolean values. Series will have the same name and index. DatetimeIndex will have the same name. See also is_year_end Similar property indicating the last day of the year. Examples This method is available on Series with datetime values under the .dt accessor, and directly on DatetimeIndex. >>> dates = pd.Series(pd.date_range("2017-12-30", periods=3)) >>> dates 0 2017-12-30 1 2017-12-31 2 2018-01-01 dtype: datetime64[ns] >>> dates.dt.is_year_start 0 False 1 False 2 True dtype: bool >>> idx = pd.date_range("2017-12-30", periods=3) >>> idx DatetimeIndex(['2017-12-30', '2017-12-31', '2018-01-01'], dtype='datetime64[ns]', freq='D') >>> idx.is_year_start array([False, False, True])
pandas.reference.api.pandas.series.dt.is_year_start
pandas.Series.dt.microsecond Series.dt.microsecond The microseconds of the datetime. Examples >>> datetime_series = pd.Series( ... pd.date_range("2000-01-01", periods=3, freq="us") ... ) >>> datetime_series 0 2000-01-01 00:00:00.000000 1 2000-01-01 00:00:00.000001 2 2000-01-01 00:00:00.000002 dtype: datetime64[ns] >>> datetime_series.dt.microsecond 0 0 1 1 2 2 dtype: int64
pandas.reference.api.pandas.series.dt.microsecond
pandas.Series.dt.microseconds Series.dt.microseconds Number of microseconds (>= 0 and less than 1 second) for each element.
pandas.reference.api.pandas.series.dt.microseconds
pandas.Series.dt.minute Series.dt.minute The minutes of the datetime. Examples >>> datetime_series = pd.Series( ... pd.date_range("2000-01-01", periods=3, freq="T") ... ) >>> datetime_series 0 2000-01-01 00:00:00 1 2000-01-01 00:01:00 2 2000-01-01 00:02:00 dtype: datetime64[ns] >>> datetime_series.dt.minute 0 0 1 1 2 2 dtype: int64
pandas.reference.api.pandas.series.dt.minute
pandas.Series.dt.month Series.dt.month The month as January=1, December=12. Examples >>> datetime_series = pd.Series( ... pd.date_range("2000-01-01", periods=3, freq="M") ... ) >>> datetime_series 0 2000-01-31 1 2000-02-29 2 2000-03-31 dtype: datetime64[ns] >>> datetime_series.dt.month 0 1 1 2 2 3 dtype: int64
pandas.reference.api.pandas.series.dt.month
pandas.Series.dt.month_name Series.dt.month_name(*args, **kwargs)[source] Return the month names of the DateTimeIndex with specified locale. Parameters locale:str, optional Locale determining the language in which to return the month name. Default is English locale. Returns Index Index of month names. Examples >>> idx = pd.date_range(start='2018-01', freq='M', periods=3) >>> idx DatetimeIndex(['2018-01-31', '2018-02-28', '2018-03-31'], dtype='datetime64[ns]', freq='M') >>> idx.month_name() Index(['January', 'February', 'March'], dtype='object')
pandas.reference.api.pandas.series.dt.month_name
pandas.Series.dt.nanosecond Series.dt.nanosecond The nanoseconds of the datetime. Examples >>> datetime_series = pd.Series( ... pd.date_range("2000-01-01", periods=3, freq="ns") ... ) >>> datetime_series 0 2000-01-01 00:00:00.000000000 1 2000-01-01 00:00:00.000000001 2 2000-01-01 00:00:00.000000002 dtype: datetime64[ns] >>> datetime_series.dt.nanosecond 0 0 1 1 2 2 dtype: int64
pandas.reference.api.pandas.series.dt.nanosecond
pandas.Series.dt.nanoseconds Series.dt.nanoseconds Number of nanoseconds (>= 0 and less than 1 microsecond) for each element.
pandas.reference.api.pandas.series.dt.nanoseconds
pandas.Series.dt.normalize Series.dt.normalize(*args, **kwargs)[source] Convert times to midnight. The time component of the date-time is converted to midnight i.e. 00:00:00. This is useful in cases, when the time does not matter. Length is unaltered. The timezones are unaffected. This method is available on Series with datetime values under the .dt accessor, and directly on Datetime Array/Index. Returns DatetimeArray, DatetimeIndex or Series The same type as the original data. Series will have the same name and index. DatetimeIndex will have the same name. See also floor Floor the datetimes to the specified freq. ceil Ceil the datetimes to the specified freq. round Round the datetimes to the specified freq. Examples >>> idx = pd.date_range(start='2014-08-01 10:00', freq='H', ... periods=3, tz='Asia/Calcutta') >>> idx DatetimeIndex(['2014-08-01 10:00:00+05:30', '2014-08-01 11:00:00+05:30', '2014-08-01 12:00:00+05:30'], dtype='datetime64[ns, Asia/Calcutta]', freq='H') >>> idx.normalize() DatetimeIndex(['2014-08-01 00:00:00+05:30', '2014-08-01 00:00:00+05:30', '2014-08-01 00:00:00+05:30'], dtype='datetime64[ns, Asia/Calcutta]', freq=None)
pandas.reference.api.pandas.series.dt.normalize
pandas.Series.dt.quarter Series.dt.quarter The quarter of the date.
pandas.reference.api.pandas.series.dt.quarter
pandas.Series.dt.qyear Series.dt.qyear
pandas.reference.api.pandas.series.dt.qyear
pandas.Series.dt.round Series.dt.round(*args, **kwargs)[source] Perform round operation on the data to the specified freq. Parameters freq:str or Offset The frequency level to round the index to. Must be a fixed frequency like ‘S’ (second) not ‘ME’ (month end). See frequency aliases for a list of possible freq values. ambiguous:‘infer’, bool-ndarray, ‘NaT’, default ‘raise’ Only relevant for DatetimeIndex: ‘infer’ will attempt to infer fall dst-transition hours based on order bool-ndarray where True signifies a DST time, False designates a non-DST time (note that this flag is only applicable for ambiguous times) ‘NaT’ will return NaT where there are ambiguous times ‘raise’ will raise an AmbiguousTimeError if there are ambiguous times. nonexistent:‘shift_forward’, ‘shift_backward’, ‘NaT’, timedelta, default ‘raise’ A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST. ‘shift_forward’ will shift the nonexistent time forward to the closest existing time ‘shift_backward’ will shift the nonexistent time backward to the closest existing time ‘NaT’ will return NaT where there are nonexistent times timedelta objects will shift nonexistent times by the timedelta ‘raise’ will raise an NonExistentTimeError if there are nonexistent times. Returns DatetimeIndex, TimedeltaIndex, or Series Index of the same type for a DatetimeIndex or TimedeltaIndex, or a Series with the same index for a Series. Raises ValueError if the freq cannot be converted. Notes If the timestamps have a timezone, rounding will take place relative to the local (“wall”) time and re-localized to the same timezone. When rounding near daylight savings time, use nonexistent and ambiguous to control the re-localization behavior. Examples DatetimeIndex >>> rng = pd.date_range('1/1/2018 11:59:00', periods=3, freq='min') >>> rng DatetimeIndex(['2018-01-01 11:59:00', '2018-01-01 12:00:00', '2018-01-01 12:01:00'], dtype='datetime64[ns]', freq='T') >>> rng.round('H') DatetimeIndex(['2018-01-01 12:00:00', '2018-01-01 12:00:00', '2018-01-01 12:00:00'], dtype='datetime64[ns]', freq=None) Series >>> pd.Series(rng).dt.round("H") 0 2018-01-01 12:00:00 1 2018-01-01 12:00:00 2 2018-01-01 12:00:00 dtype: datetime64[ns] When rounding near a daylight savings time transition, use ambiguous or nonexistent to control how the timestamp should be re-localized. >>> rng_tz = pd.DatetimeIndex(["2021-10-31 03:30:00"], tz="Europe/Amsterdam") >>> rng_tz.floor("2H", ambiguous=False) DatetimeIndex(['2021-10-31 02:00:00+01:00'], dtype='datetime64[ns, Europe/Amsterdam]', freq=None) >>> rng_tz.floor("2H", ambiguous=True) DatetimeIndex(['2021-10-31 02:00:00+02:00'], dtype='datetime64[ns, Europe/Amsterdam]', freq=None)
pandas.reference.api.pandas.series.dt.round
pandas.Series.dt.second Series.dt.second The seconds of the datetime. Examples >>> datetime_series = pd.Series( ... pd.date_range("2000-01-01", periods=3, freq="s") ... ) >>> datetime_series 0 2000-01-01 00:00:00 1 2000-01-01 00:00:01 2 2000-01-01 00:00:02 dtype: datetime64[ns] >>> datetime_series.dt.second 0 0 1 1 2 2 dtype: int64
pandas.reference.api.pandas.series.dt.second
pandas.Series.dt.seconds Series.dt.seconds Number of seconds (>= 0 and less than 1 day) for each element.
pandas.reference.api.pandas.series.dt.seconds
pandas.Series.dt.start_time Series.dt.start_time
pandas.reference.api.pandas.series.dt.start_time
pandas.Series.dt.strftime Series.dt.strftime(*args, **kwargs)[source] Convert to Index using specified date_format. Return an Index of formatted strings specified by date_format, which supports the same string format as the python standard library. Details of the string format can be found in python string format doc. Parameters date_format:str Date format string (e.g. “%Y-%m-%d”). Returns ndarray[object] NumPy ndarray of formatted strings. See also to_datetime Convert the given argument to datetime. DatetimeIndex.normalize Return DatetimeIndex with times to midnight. DatetimeIndex.round Round the DatetimeIndex to the specified freq. DatetimeIndex.floor Floor the DatetimeIndex to the specified freq. Examples >>> rng = pd.date_range(pd.Timestamp("2018-03-10 09:00"), ... periods=3, freq='s') >>> rng.strftime('%B %d, %Y, %r') Index(['March 10, 2018, 09:00:00 AM', 'March 10, 2018, 09:00:01 AM', 'March 10, 2018, 09:00:02 AM'], dtype='object')
pandas.reference.api.pandas.series.dt.strftime
pandas.Series.dt.time Series.dt.time Returns numpy array of datetime.time objects. The time part of the Timestamps.
pandas.reference.api.pandas.series.dt.time
pandas.Series.dt.timetz Series.dt.timetz Returns numpy array of datetime.time objects with timezone information. The time part of the Timestamps.
pandas.reference.api.pandas.series.dt.timetz
pandas.Series.dt.to_period Series.dt.to_period(*args, **kwargs)[source] Cast to PeriodArray/Index at a particular frequency. Converts DatetimeArray/Index to PeriodArray/Index. Parameters freq:str or Offset, optional One of pandas’ offset strings or an Offset object. Will be inferred by default. Returns PeriodArray/Index Raises ValueError When converting a DatetimeArray/Index with non-regular values, so that a frequency cannot be inferred. See also PeriodIndex Immutable ndarray holding ordinal values. DatetimeIndex.to_pydatetime Return DatetimeIndex as object. Examples >>> df = pd.DataFrame({"y": [1, 2, 3]}, ... index=pd.to_datetime(["2000-03-31 00:00:00", ... "2000-05-31 00:00:00", ... "2000-08-31 00:00:00"])) >>> df.index.to_period("M") PeriodIndex(['2000-03', '2000-05', '2000-08'], dtype='period[M]') Infer the daily frequency >>> idx = pd.date_range("2017-01-01", periods=2) >>> idx.to_period() PeriodIndex(['2017-01-01', '2017-01-02'], dtype='period[D]')
pandas.reference.api.pandas.series.dt.to_period
pandas.Series.dt.to_pydatetime Series.dt.to_pydatetime()[source] Return the data as an array of datetime.datetime objects. Timezone information is retained if present. Warning Python’s datetime uses microsecond resolution, which is lower than pandas (nanosecond). The values are truncated. Returns numpy.ndarray Object dtype array containing native Python datetime objects. See also datetime.datetime Standard library value for a datetime. Examples >>> s = pd.Series(pd.date_range('20180310', periods=2)) >>> s 0 2018-03-10 1 2018-03-11 dtype: datetime64[ns] >>> s.dt.to_pydatetime() array([datetime.datetime(2018, 3, 10, 0, 0), datetime.datetime(2018, 3, 11, 0, 0)], dtype=object) pandas’ nanosecond precision is truncated to microseconds. >>> s = pd.Series(pd.date_range('20180310', periods=2, freq='ns')) >>> s 0 2018-03-10 00:00:00.000000000 1 2018-03-10 00:00:00.000000001 dtype: datetime64[ns] >>> s.dt.to_pydatetime() array([datetime.datetime(2018, 3, 10, 0, 0), datetime.datetime(2018, 3, 10, 0, 0)], dtype=object)
pandas.reference.api.pandas.series.dt.to_pydatetime
pandas.Series.dt.to_pytimedelta Series.dt.to_pytimedelta()[source] Return an array of native datetime.timedelta objects. Python’s standard datetime library uses a different representation timedelta’s. This method converts a Series of pandas Timedeltas to datetime.timedelta format with the same length as the original Series. Returns numpy.ndarray Array of 1D containing data with datetime.timedelta type. See also datetime.timedelta A duration expressing the difference between two date, time, or datetime. Examples >>> s = pd.Series(pd.to_timedelta(np.arange(5), unit="d")) >>> s 0 0 days 1 1 days 2 2 days 3 3 days 4 4 days dtype: timedelta64[ns] >>> s.dt.to_pytimedelta() array([datetime.timedelta(0), datetime.timedelta(days=1), datetime.timedelta(days=2), datetime.timedelta(days=3), datetime.timedelta(days=4)], dtype=object)
pandas.reference.api.pandas.series.dt.to_pytimedelta
pandas.Series.dt.total_seconds Series.dt.total_seconds(*args, **kwargs)[source] Return total duration of each element expressed in seconds. This method is available directly on TimedeltaArray, TimedeltaIndex and on Series containing timedelta values under the .dt namespace. Returns seconds:[ndarray, Float64Index, Series] When the calling object is a TimedeltaArray, the return type is ndarray. When the calling object is a TimedeltaIndex, the return type is a Float64Index. When the calling object is a Series, the return type is Series of type float64 whose index is the same as the original. See also datetime.timedelta.total_seconds Standard library version of this method. TimedeltaIndex.components Return a DataFrame with components of each Timedelta. Examples Series >>> s = pd.Series(pd.to_timedelta(np.arange(5), unit='d')) >>> s 0 0 days 1 1 days 2 2 days 3 3 days 4 4 days dtype: timedelta64[ns] >>> s.dt.total_seconds() 0 0.0 1 86400.0 2 172800.0 3 259200.0 4 345600.0 dtype: float64 TimedeltaIndex >>> idx = pd.to_timedelta(np.arange(5), unit='d') >>> idx TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'], dtype='timedelta64[ns]', freq=None) >>> idx.total_seconds() Float64Index([0.0, 86400.0, 172800.0, 259200.00000000003, 345600.0], dtype='float64')
pandas.reference.api.pandas.series.dt.total_seconds
pandas.Series.dt.tz Series.dt.tz Return the timezone. Returns datetime.tzinfo, pytz.tzinfo.BaseTZInfo, dateutil.tz.tz.tzfile, or None Returns None when the array is tz-naive.
pandas.reference.api.pandas.series.dt.tz
pandas.Series.dt.tz_convert Series.dt.tz_convert(*args, **kwargs)[source] Convert tz-aware Datetime Array/Index from one time zone to another. Parameters tz:str, pytz.timezone, dateutil.tz.tzfile or None Time zone for time. Corresponding timestamps would be converted to this time zone of the Datetime Array/Index. A tz of None will convert to UTC and remove the timezone information. Returns Array or Index Raises TypeError If Datetime Array/Index is tz-naive. See also DatetimeIndex.tz A timezone that has a variable offset from UTC. DatetimeIndex.tz_localize Localize tz-naive DatetimeIndex to a given time zone, or remove timezone from a tz-aware DatetimeIndex. Examples With the tz parameter, we can change the DatetimeIndex to other time zones: >>> dti = pd.date_range(start='2014-08-01 09:00', ... freq='H', periods=3, tz='Europe/Berlin') >>> dti DatetimeIndex(['2014-08-01 09:00:00+02:00', '2014-08-01 10:00:00+02:00', '2014-08-01 11:00:00+02:00'], dtype='datetime64[ns, Europe/Berlin]', freq='H') >>> dti.tz_convert('US/Central') DatetimeIndex(['2014-08-01 02:00:00-05:00', '2014-08-01 03:00:00-05:00', '2014-08-01 04:00:00-05:00'], dtype='datetime64[ns, US/Central]', freq='H') With the tz=None, we can remove the timezone (after converting to UTC if necessary): >>> dti = pd.date_range(start='2014-08-01 09:00', freq='H', ... periods=3, tz='Europe/Berlin') >>> dti DatetimeIndex(['2014-08-01 09:00:00+02:00', '2014-08-01 10:00:00+02:00', '2014-08-01 11:00:00+02:00'], dtype='datetime64[ns, Europe/Berlin]', freq='H') >>> dti.tz_convert(None) DatetimeIndex(['2014-08-01 07:00:00', '2014-08-01 08:00:00', '2014-08-01 09:00:00'], dtype='datetime64[ns]', freq='H')
pandas.reference.api.pandas.series.dt.tz_convert
pandas.Series.dt.tz_localize Series.dt.tz_localize(*args, **kwargs)[source] Localize tz-naive Datetime Array/Index to tz-aware Datetime Array/Index. This method takes a time zone (tz) naive Datetime Array/Index object and makes this time zone aware. It does not move the time to another time zone. This method can also be used to do the inverse – to create a time zone unaware object from an aware object. To that end, pass tz=None. Parameters tz:str, pytz.timezone, dateutil.tz.tzfile or None Time zone to convert timestamps to. Passing None will remove the time zone information preserving local time. ambiguous:‘infer’, ‘NaT’, bool array, default ‘raise’ When clocks moved backward due to DST, ambiguous times may arise. For example in Central European Time (UTC+01), when going from 03:00 DST to 02:00 non-DST, 02:30:00 local time occurs both at 00:30:00 UTC and at 01:30:00 UTC. In such a situation, the ambiguous parameter dictates how ambiguous times should be handled. ‘infer’ will attempt to infer fall dst-transition hours based on order bool-ndarray where True signifies a DST time, False signifies a non-DST time (note that this flag is only applicable for ambiguous times) ‘NaT’ will return NaT where there are ambiguous times ‘raise’ will raise an AmbiguousTimeError if there are ambiguous times. nonexistent:‘shift_forward’, ‘shift_backward, ‘NaT’, timedelta, default ‘raise’ A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST. ‘shift_forward’ will shift the nonexistent time forward to the closest existing time ‘shift_backward’ will shift the nonexistent time backward to the closest existing time ‘NaT’ will return NaT where there are nonexistent times timedelta objects will shift nonexistent times by the timedelta ‘raise’ will raise an NonExistentTimeError if there are nonexistent times. Returns Same type as self Array/Index converted to the specified time zone. Raises TypeError If the Datetime Array/Index is tz-aware and tz is not None. See also DatetimeIndex.tz_convert Convert tz-aware DatetimeIndex from one time zone to another. Examples >>> tz_naive = pd.date_range('2018-03-01 09:00', periods=3) >>> tz_naive DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00', '2018-03-03 09:00:00'], dtype='datetime64[ns]', freq='D') Localize DatetimeIndex in US/Eastern time zone: >>> tz_aware = tz_naive.tz_localize(tz='US/Eastern') >>> tz_aware DatetimeIndex(['2018-03-01 09:00:00-05:00', '2018-03-02 09:00:00-05:00', '2018-03-03 09:00:00-05:00'], dtype='datetime64[ns, US/Eastern]', freq=None) With the tz=None, we can remove the time zone information while keeping the local time (not converted to UTC): >>> tz_aware.tz_localize(None) DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00', '2018-03-03 09:00:00'], dtype='datetime64[ns]', freq=None) Be careful with DST changes. When there is sequential data, pandas can infer the DST time: >>> s = pd.to_datetime(pd.Series(['2018-10-28 01:30:00', ... '2018-10-28 02:00:00', ... '2018-10-28 02:30:00', ... '2018-10-28 02:00:00', ... '2018-10-28 02:30:00', ... '2018-10-28 03:00:00', ... '2018-10-28 03:30:00'])) >>> s.dt.tz_localize('CET', ambiguous='infer') 0 2018-10-28 01:30:00+02:00 1 2018-10-28 02:00:00+02:00 2 2018-10-28 02:30:00+02:00 3 2018-10-28 02:00:00+01:00 4 2018-10-28 02:30:00+01:00 5 2018-10-28 03:00:00+01:00 6 2018-10-28 03:30:00+01:00 dtype: datetime64[ns, CET] In some cases, inferring the DST is impossible. In such cases, you can pass an ndarray to the ambiguous parameter to set the DST explicitly >>> s = pd.to_datetime(pd.Series(['2018-10-28 01:20:00', ... '2018-10-28 02:36:00', ... '2018-10-28 03:46:00'])) >>> s.dt.tz_localize('CET', ambiguous=np.array([True, True, False])) 0 2018-10-28 01:20:00+02:00 1 2018-10-28 02:36:00+02:00 2 2018-10-28 03:46:00+01:00 dtype: datetime64[ns, CET] If the DST transition causes nonexistent times, you can shift these dates forward or backwards with a timedelta object or ‘shift_forward’ or ‘shift_backwards’. >>> s = pd.to_datetime(pd.Series(['2015-03-29 02:30:00', ... '2015-03-29 03:30:00'])) >>> s.dt.tz_localize('Europe/Warsaw', nonexistent='shift_forward') 0 2015-03-29 03:00:00+02:00 1 2015-03-29 03:30:00+02:00 dtype: datetime64[ns, Europe/Warsaw] >>> s.dt.tz_localize('Europe/Warsaw', nonexistent='shift_backward') 0 2015-03-29 01:59:59.999999999+01:00 1 2015-03-29 03:30:00+02:00 dtype: datetime64[ns, Europe/Warsaw] >>> s.dt.tz_localize('Europe/Warsaw', nonexistent=pd.Timedelta('1H')) 0 2015-03-29 03:30:00+02:00 1 2015-03-29 03:30:00+02:00 dtype: datetime64[ns, Europe/Warsaw]
pandas.reference.api.pandas.series.dt.tz_localize
pandas.Series.dt.week Series.dt.week The week ordinal of the year. Deprecated since version 1.1.0. Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.
pandas.reference.api.pandas.series.dt.week
pandas.Series.dt.weekday Series.dt.weekday The day of the week with Monday=0, Sunday=6. Return the day of the week. It is assumed the week starts on Monday, which is denoted by 0 and ends on Sunday which is denoted by 6. This method is available on both Series with datetime values (using the dt accessor) or DatetimeIndex. Returns Series or Index Containing integers indicating the day number. See also Series.dt.dayofweek Alias. Series.dt.weekday Alias. Series.dt.day_name Returns the name of the day of the week. Examples >>> s = pd.date_range('2016-12-31', '2017-01-08', freq='D').to_series() >>> s.dt.dayofweek 2016-12-31 5 2017-01-01 6 2017-01-02 0 2017-01-03 1 2017-01-04 2 2017-01-05 3 2017-01-06 4 2017-01-07 5 2017-01-08 6 Freq: D, dtype: int64
pandas.reference.api.pandas.series.dt.weekday
pandas.Series.dt.weekofyear Series.dt.weekofyear The week ordinal of the year. Deprecated since version 1.1.0. Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead.
pandas.reference.api.pandas.series.dt.weekofyear
pandas.Series.dt.year Series.dt.year The year of the datetime. Examples >>> datetime_series = pd.Series( ... pd.date_range("2000-01-01", periods=3, freq="Y") ... ) >>> datetime_series 0 2000-12-31 1 2001-12-31 2 2002-12-31 dtype: datetime64[ns] >>> datetime_series.dt.year 0 2000 1 2001 2 2002 dtype: int64
pandas.reference.api.pandas.series.dt.year
pandas.Series.dtype propertySeries.dtype Return the dtype object of the underlying data.
pandas.reference.api.pandas.series.dtype
pandas.Series.dtypes propertySeries.dtypes Return the dtype object of the underlying data.
pandas.reference.api.pandas.series.dtypes
pandas.Series.duplicated Series.duplicated(keep='first')[source] Indicate duplicate Series values. Duplicated values are indicated as True values in the resulting Series. Either all duplicates, all except the first or all except the last occurrence of duplicates can be indicated. Parameters keep:{‘first’, ‘last’, False}, default ‘first’ Method to handle dropping duplicates: ‘first’ : Mark duplicates as True except for the first occurrence. ‘last’ : Mark duplicates as True except for the last occurrence. False : Mark all duplicates as True. Returns Series[bool] Series indicating whether each value has occurred in the preceding values. See also Index.duplicated Equivalent method on pandas.Index. DataFrame.duplicated Equivalent method on pandas.DataFrame. Series.drop_duplicates Remove duplicate values from Series. Examples By default, for each set of duplicated values, the first occurrence is set on False and all others on True: >>> animals = pd.Series(['lama', 'cow', 'lama', 'beetle', 'lama']) >>> animals.duplicated() 0 False 1 False 2 True 3 False 4 True dtype: bool which is equivalent to >>> animals.duplicated(keep='first') 0 False 1 False 2 True 3 False 4 True dtype: bool By using ‘last’, the last occurrence of each set of duplicated values is set on False and all others on True: >>> animals.duplicated(keep='last') 0 True 1 False 2 True 3 False 4 False dtype: bool By setting keep on False, all duplicates are True: >>> animals.duplicated(keep=False) 0 True 1 False 2 True 3 False 4 True dtype: bool
pandas.reference.api.pandas.series.duplicated
pandas.Series.empty propertySeries.empty Indicator whether Series/DataFrame is empty. True if Series/DataFrame is entirely empty (no items), meaning any of the axes are of length 0. Returns bool If Series/DataFrame is empty, return True, if not return False. See also Series.dropna Return series without null values. DataFrame.dropna Return DataFrame with labels on given axis omitted where (all or any) data are missing. Notes If Series/DataFrame contains only NaNs, it is still not considered empty. See the example below. Examples An example of an actual empty DataFrame. Notice the index is empty: >>> df_empty = pd.DataFrame({'A' : []}) >>> df_empty Empty DataFrame Columns: [A] Index: [] >>> df_empty.empty True If we only have NaNs in our DataFrame, it is not considered empty! We will need to drop the NaNs to make the DataFrame empty: >>> df = pd.DataFrame({'A' : [np.nan]}) >>> df A 0 NaN >>> df.empty False >>> df.dropna().empty True >>> ser_empty = pd.Series({'A' : []}) >>> ser_empty A [] dtype: object >>> ser_empty.empty False >>> ser_empty = pd.Series() >>> ser_empty.empty True
pandas.reference.api.pandas.series.empty
pandas.Series.eq Series.eq(other, level=None, fill_value=None, axis=0)[source] Return Equal to of series and other, element-wise (binary operator eq). Equivalent to series == other, but with support to substitute a fill_value for missing data in either one of the inputs. Parameters other:Series or scalar value fill_value:None or float value, default None (NaN) Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing. level:int or name Broadcast across a level, matching Index values on the passed MultiIndex level. Returns Series The result of the operation. Examples >>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd']) >>> a a 1.0 b 1.0 c 1.0 d NaN dtype: float64 >>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e']) >>> b a 1.0 b NaN d 1.0 e NaN dtype: float64 >>> a.eq(b, fill_value=0) a True b False c False d False e False dtype: bool
pandas.reference.api.pandas.series.eq
pandas.Series.equals Series.equals(other)[source] Test whether two objects contain the same elements. This function allows two Series or DataFrames to be compared against each other to see if they have the same shape and elements. NaNs in the same location are considered equal. The row/column index do not need to have the same type, as long as the values are considered equal. Corresponding columns must be of the same dtype. Parameters other:Series or DataFrame The other Series or DataFrame to be compared with the first. Returns bool True if all elements are the same in both objects, False otherwise. See also Series.eq Compare two Series objects of the same length and return a Series where each element is True if the element in each Series is equal, False otherwise. DataFrame.eq Compare two DataFrame objects of the same shape and return a DataFrame where each element is True if the respective element in each DataFrame is equal, False otherwise. testing.assert_series_equal Raises an AssertionError if left and right are not equal. Provides an easy interface to ignore inequality in dtypes, indexes and precision among others. testing.assert_frame_equal Like assert_series_equal, but targets DataFrames. numpy.array_equal Return True if two arrays have the same shape and elements, False otherwise. Examples >>> df = pd.DataFrame({1: [10], 2: [20]}) >>> df 1 2 0 10 20 DataFrames df and exactly_equal have the same types and values for their elements and column labels, which will return True. >>> exactly_equal = pd.DataFrame({1: [10], 2: [20]}) >>> exactly_equal 1 2 0 10 20 >>> df.equals(exactly_equal) True DataFrames df and different_column_type have the same element types and values, but have different types for the column labels, which will still return True. >>> different_column_type = pd.DataFrame({1.0: [10], 2.0: [20]}) >>> different_column_type 1.0 2.0 0 10 20 >>> df.equals(different_column_type) True DataFrames df and different_data_type have different types for the same values for their elements, and will return False even though their column labels are the same values and types. >>> different_data_type = pd.DataFrame({1: [10.0], 2: [20.0]}) >>> different_data_type 1 2 0 10.0 20.0 >>> df.equals(different_data_type) False
pandas.reference.api.pandas.series.equals
pandas.Series.ewm Series.ewm(com=None, span=None, halflife=None, alpha=None, min_periods=0, adjust=True, ignore_na=False, axis=0, times=None, method='single')[source] Provide exponentially weighted (EW) calculations. Exactly one parameter: com, span, halflife, or alpha must be provided. Parameters com:float, optional Specify decay in terms of center of mass \(\alpha = 1 / (1 + com)\), for \(com \geq 0\). span:float, optional Specify decay in terms of span \(\alpha = 2 / (span + 1)\), for \(span \geq 1\). halflife:float, str, timedelta, optional Specify decay in terms of half-life \(\alpha = 1 - \exp\left(-\ln(2) / halflife\right)\), for \(halflife > 0\). If times is specified, the time unit (str or timedelta) over which an observation decays to half its value. Only applicable to mean(), and halflife value will not apply to the other functions. New in version 1.1.0. alpha:float, optional Specify smoothing factor \(\alpha\) directly \(0 < \alpha \leq 1\). min_periods:int, default 0 Minimum number of observations in window required to have a value; otherwise, result is np.nan. adjust:bool, default True Divide by decaying adjustment factor in beginning periods to account for imbalance in relative weightings (viewing EWMA as a moving average). When adjust=True (default), the EW function is calculated using weights \(w_i = (1 - \alpha)^i\). For example, the EW moving average of the series [\(x_0, x_1, ..., x_t\)] would be: \[y_t = \frac{x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ... + (1 - \alpha)^t x_0}{1 + (1 - \alpha) + (1 - \alpha)^2 + ... + (1 - \alpha)^t}\] When adjust=False, the exponentially weighted function is calculated recursively: \[\begin{split}\begin{split} y_0 &= x_0\\ y_t &= (1 - \alpha) y_{t-1} + \alpha x_t, \end{split}\end{split}\] ignore_na:bool, default False Ignore missing values when calculating weights. When ignore_na=False (default), weights are based on absolute positions. For example, the weights of \(x_0\) and \(x_2\) used in calculating the final weighted average of [\(x_0\), None, \(x_2\)] are \((1-\alpha)^2\) and \(1\) if adjust=True, and \((1-\alpha)^2\) and \(\alpha\) if adjust=False. When ignore_na=True, weights are based on relative positions. For example, the weights of \(x_0\) and \(x_2\) used in calculating the final weighted average of [\(x_0\), None, \(x_2\)] are \(1-\alpha\) and \(1\) if adjust=True, and \(1-\alpha\) and \(\alpha\) if adjust=False. axis:{0, 1}, default 0 If 0 or 'index', calculate across the rows. If 1 or 'columns', calculate across the columns. times:str, np.ndarray, Series, default None New in version 1.1.0. Only applicable to mean(). Times corresponding to the observations. Must be monotonically increasing and datetime64[ns] dtype. If 1-D array like, a sequence with the same shape as the observations. Deprecated since version 1.4.0: If str, the name of the column in the DataFrame representing the times. method:str {‘single’, ‘table’}, default ‘single’ New in version 1.4.0. Execute the rolling operation per single column or row ('single') or over the entire object ('table'). This argument is only implemented when specifying engine='numba' in the method call. Only applicable to mean() Returns ExponentialMovingWindow subclass See also rolling Provides rolling window calculations. expanding Provides expanding transformations. Notes See Windowing Operations for further usage details and examples. Examples >>> df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]}) >>> df B 0 0.0 1 1.0 2 2.0 3 NaN 4 4.0 >>> df.ewm(com=0.5).mean() B 0 0.000000 1 0.750000 2 1.615385 3 1.615385 4 3.670213 >>> df.ewm(alpha=2 / 3).mean() B 0 0.000000 1 0.750000 2 1.615385 3 1.615385 4 3.670213 adjust >>> df.ewm(com=0.5, adjust=True).mean() B 0 0.000000 1 0.750000 2 1.615385 3 1.615385 4 3.670213 >>> df.ewm(com=0.5, adjust=False).mean() B 0 0.000000 1 0.666667 2 1.555556 3 1.555556 4 3.650794 ignore_na >>> df.ewm(com=0.5, ignore_na=True).mean() B 0 0.000000 1 0.750000 2 1.615385 3 1.615385 4 3.225000 >>> df.ewm(com=0.5, ignore_na=False).mean() B 0 0.000000 1 0.750000 2 1.615385 3 1.615385 4 3.670213 times Exponentially weighted mean with weights calculated with a timedelta halflife relative to times. >>> times = ['2020-01-01', '2020-01-03', '2020-01-10', '2020-01-15', '2020-01-17'] >>> df.ewm(halflife='4 days', times=pd.DatetimeIndex(times)).mean() B 0 0.000000 1 0.585786 2 1.523889 3 1.523889 4 3.233686
pandas.reference.api.pandas.series.ewm
pandas.Series.expanding Series.expanding(min_periods=1, center=None, axis=0, method='single')[source] Provide expanding window calculations. Parameters min_periods:int, default 1 Minimum number of observations in window required to have a value; otherwise, result is np.nan. center:bool, default False If False, set the window labels as the right edge of the window index. If True, set the window labels as the center of the window index. Deprecated since version 1.1.0. axis:int or str, default 0 If 0 or 'index', roll across the rows. If 1 or 'columns', roll across the columns. method:str {‘single’, ‘table’}, default ‘single’ Execute the rolling operation per single column or row ('single') or over the entire object ('table'). This argument is only implemented when specifying engine='numba' in the method call. New in version 1.3.0. Returns Expanding subclass See also rolling Provides rolling window calculations. ewm Provides exponential weighted functions. Notes See Windowing Operations for further usage details and examples. Examples >>> df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]}) >>> df B 0 0.0 1 1.0 2 2.0 3 NaN 4 4.0 min_periods Expanding sum with 1 vs 3 observations needed to calculate a value. >>> df.expanding(1).sum() B 0 0.0 1 1.0 2 3.0 3 3.0 4 7.0 >>> df.expanding(3).sum() B 0 NaN 1 NaN 2 3.0 3 3.0 4 7.0
pandas.reference.api.pandas.series.expanding
pandas.Series.explode Series.explode(ignore_index=False)[source] Transform each element of a list-like to a row. New in version 0.25.0. Parameters ignore_index:bool, default False If True, the resulting index will be labeled 0, 1, …, n - 1. New in version 1.1.0. Returns Series Exploded lists to rows; index will be duplicated for these rows. See also Series.str.split Split string values on specified separator. Series.unstack Unstack, a.k.a. pivot, Series with MultiIndex to produce DataFrame. DataFrame.melt Unpivot a DataFrame from wide format to long format. DataFrame.explode Explode a DataFrame from list-like columns to long format. Notes This routine will explode list-likes including lists, tuples, sets, Series, and np.ndarray. The result dtype of the subset rows will be object. Scalars will be returned unchanged, and empty list-likes will result in a np.nan for that row. In addition, the ordering of elements in the output will be non-deterministic when exploding sets. Examples >>> s = pd.Series([[1, 2, 3], 'foo', [], [3, 4]]) >>> s 0 [1, 2, 3] 1 foo 2 [] 3 [3, 4] dtype: object >>> s.explode() 0 1 0 2 0 3 1 foo 2 NaN 3 3 3 4 dtype: object
pandas.reference.api.pandas.series.explode
pandas.Series.factorize Series.factorize(sort=False, na_sentinel=- 1)[source] Encode the object as an enumerated type or categorical variable. This method is useful for obtaining a numeric representation of an array when all that matters is identifying distinct values. factorize is available as both a top-level function pandas.factorize(), and as a method Series.factorize() and Index.factorize(). Parameters sort:bool, default False Sort uniques and shuffle codes to maintain the relationship. na_sentinel:int or None, default -1 Value to mark “not found”. If None, will not drop the NaN from the uniques of the values. Changed in version 1.1.2. Returns codes:ndarray An integer ndarray that’s an indexer into uniques. uniques.take(codes) will have the same values as values. uniques:ndarray, Index, or Categorical The unique valid values. When values is Categorical, uniques is a Categorical. When values is some other pandas object, an Index is returned. Otherwise, a 1-D ndarray is returned. Note Even if there’s a missing value in values, uniques will not contain an entry for it. See also cut Discretize continuous-valued array. unique Find the unique value in an array. Examples These examples all show factorize as a top-level method like pd.factorize(values). The results are identical for methods like Series.factorize(). >>> codes, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b']) >>> codes array([0, 0, 1, 2, 0]...) >>> uniques array(['b', 'a', 'c'], dtype=object) With sort=True, the uniques will be sorted, and codes will be shuffled so that the relationship is the maintained. >>> codes, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b'], sort=True) >>> codes array([1, 1, 0, 2, 1]...) >>> uniques array(['a', 'b', 'c'], dtype=object) Missing values are indicated in codes with na_sentinel (-1 by default). Note that missing values are never included in uniques. >>> codes, uniques = pd.factorize(['b', None, 'a', 'c', 'b']) >>> codes array([ 0, -1, 1, 2, 0]...) >>> uniques array(['b', 'a', 'c'], dtype=object) Thus far, we’ve only factorized lists (which are internally coerced to NumPy arrays). When factorizing pandas objects, the type of uniques will differ. For Categoricals, a Categorical is returned. >>> cat = pd.Categorical(['a', 'a', 'c'], categories=['a', 'b', 'c']) >>> codes, uniques = pd.factorize(cat) >>> codes array([0, 0, 1]...) >>> uniques ['a', 'c'] Categories (3, object): ['a', 'b', 'c'] Notice that 'b' is in uniques.categories, despite not being present in cat.values. For all other pandas objects, an Index of the appropriate type is returned. >>> cat = pd.Series(['a', 'a', 'c']) >>> codes, uniques = pd.factorize(cat) >>> codes array([0, 0, 1]...) >>> uniques Index(['a', 'c'], dtype='object') If NaN is in the values, and we want to include NaN in the uniques of the values, it can be achieved by setting na_sentinel=None. >>> values = np.array([1, 2, 1, np.nan]) >>> codes, uniques = pd.factorize(values) # default: na_sentinel=-1 >>> codes array([ 0, 1, 0, -1]) >>> uniques array([1., 2.]) >>> codes, uniques = pd.factorize(values, na_sentinel=None) >>> codes array([0, 1, 0, 2]) >>> uniques array([ 1., 2., nan])
pandas.reference.api.pandas.series.factorize
pandas.Series.ffill Series.ffill(axis=None, inplace=False, limit=None, downcast=None)[source] Synonym for DataFrame.fillna() with method='ffill'. Returns Series/DataFrame or None Object with missing values filled or None if inplace=True.
pandas.reference.api.pandas.series.ffill
pandas.Series.fillna Series.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None)[source] Fill NA/NaN values using the specified method. Parameters value:scalar, dict, Series, or DataFrame Value to use to fill holes (e.g. 0), alternately a dict/Series/DataFrame of values specifying which value to use for each index (for a Series) or column (for a DataFrame). Values not in the dict/Series/DataFrame will not be filled. This value cannot be a list. method:{‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None}, default None Method to use for filling holes in reindexed Series pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use next valid observation to fill gap. axis:{0 or ‘index’} Axis along which to fill missing values. inplace:bool, default False If True, fill in-place. Note: this will modify any other views on this object (e.g., a no-copy slice for a column in a DataFrame). limit:int, default None If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None. downcast:dict, default is None A dict of item->dtype of what to downcast if possible, or the string ‘infer’ which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible). Returns Series or None Object with missing values filled or None if inplace=True. See also interpolate Fill NaN values using interpolation. reindex Conform object to new index. asfreq Convert TimeSeries to specified frequency. Examples >>> df = pd.DataFrame([[np.nan, 2, np.nan, 0], ... [3, 4, np.nan, 1], ... [np.nan, np.nan, np.nan, np.nan], ... [np.nan, 3, np.nan, 4]], ... columns=list("ABCD")) >>> df A B C D 0 NaN 2.0 NaN 0.0 1 3.0 4.0 NaN 1.0 2 NaN NaN NaN NaN 3 NaN 3.0 NaN 4.0 Replace all NaN elements with 0s. >>> df.fillna(0) A B C D 0 0.0 2.0 0.0 0.0 1 3.0 4.0 0.0 1.0 2 0.0 0.0 0.0 0.0 3 0.0 3.0 0.0 4.0 We can also propagate non-null values forward or backward. >>> df.fillna(method="ffill") A B C D 0 NaN 2.0 NaN 0.0 1 3.0 4.0 NaN 1.0 2 3.0 4.0 NaN 1.0 3 3.0 3.0 NaN 4.0 Replace all NaN elements in column ‘A’, ‘B’, ‘C’, and ‘D’, with 0, 1, 2, and 3 respectively. >>> values = {"A": 0, "B": 1, "C": 2, "D": 3} >>> df.fillna(value=values) A B C D 0 0.0 2.0 2.0 0.0 1 3.0 4.0 2.0 1.0 2 0.0 1.0 2.0 3.0 3 0.0 3.0 2.0 4.0 Only replace the first NaN element. >>> df.fillna(value=values, limit=1) A B C D 0 0.0 2.0 2.0 0.0 1 3.0 4.0 NaN 1.0 2 NaN 1.0 NaN 3.0 3 NaN 3.0 NaN 4.0 When filling using a DataFrame, replacement happens along the same column names and same indices >>> df2 = pd.DataFrame(np.zeros((4, 4)), columns=list("ABCE")) >>> df.fillna(df2) A B C D 0 0.0 2.0 0.0 0.0 1 3.0 4.0 0.0 1.0 2 0.0 0.0 0.0 NaN 3 0.0 3.0 0.0 4.0 Note that column D is not affected since it is not present in df2.
pandas.reference.api.pandas.series.fillna
pandas.Series.filter Series.filter(items=None, like=None, regex=None, axis=None)[source] Subset the dataframe rows or columns according to the specified index labels. Note that this routine does not filter a dataframe on its contents. The filter is applied to the labels of the index. Parameters items:list-like Keep labels from axis which are in items. like:str Keep labels from axis for which “like in label == True”. regex:str (regular expression) Keep labels from axis for which re.search(regex, label) == True. axis:{0 or ‘index’, 1 or ‘columns’, None}, default None The axis to filter on, expressed either as an index (int) or axis name (str). By default this is the info axis, ‘index’ for Series, ‘columns’ for DataFrame. Returns same type as input object See also DataFrame.loc Access a group of rows and columns by label(s) or a boolean array. Notes The items, like, and regex parameters are enforced to be mutually exclusive. axis defaults to the info axis that is used when indexing with []. Examples >>> df = pd.DataFrame(np.array(([1, 2, 3], [4, 5, 6])), ... index=['mouse', 'rabbit'], ... columns=['one', 'two', 'three']) >>> df one two three mouse 1 2 3 rabbit 4 5 6 >>> # select columns by name >>> df.filter(items=['one', 'three']) one three mouse 1 3 rabbit 4 6 >>> # select columns by regular expression >>> df.filter(regex='e$', axis=1) one three mouse 1 3 rabbit 4 6 >>> # select rows containing 'bbi' >>> df.filter(like='bbi', axis=0) one two three rabbit 4 5 6
pandas.reference.api.pandas.series.filter
pandas.Series.first Series.first(offset)[source] Select initial periods of time series data based on a date offset. When having a DataFrame with dates as index, this function can select the first few rows based on a date offset. Parameters offset:str, DateOffset or dateutil.relativedelta The offset length of the data that will be selected. For instance, ‘1M’ will display all the rows having their index within the first month. Returns Series or DataFrame A subset of the caller. Raises TypeError If the index is not a DatetimeIndex See also last Select final periods of time series based on a date offset. at_time Select values at a particular time of the day. between_time Select values between particular times of the day. Examples >>> i = pd.date_range('2018-04-09', periods=4, freq='2D') >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i) >>> ts A 2018-04-09 1 2018-04-11 2 2018-04-13 3 2018-04-15 4 Get the rows for the first 3 days: >>> ts.first('3D') A 2018-04-09 1 2018-04-11 2 Notice the data for 3 first calendar days were returned, not the first 3 days observed in the dataset, and therefore data for 2018-04-13 was not returned.
pandas.reference.api.pandas.series.first
pandas.Series.first_valid_index Series.first_valid_index()[source] Return index for first non-NA value or None, if no NA value is found. Returns scalar:type of index Notes If all elements are non-NA/null, returns None. Also returns None for empty Series/DataFrame.
pandas.reference.api.pandas.series.first_valid_index
pandas.Series.flags propertySeries.flags Get the properties associated with this pandas object. The available flags are Flags.allows_duplicate_labels See also Flags Flags that apply to pandas objects. DataFrame.attrs Global metadata applying to this dataset. Notes “Flags” differ from “metadata”. Flags reflect properties of the pandas object (the Series or DataFrame). Metadata refer to properties of the dataset, and should be stored in DataFrame.attrs. Examples >>> df = pd.DataFrame({"A": [1, 2]}) >>> df.flags <Flags(allows_duplicate_labels=True)> Flags can be get or set using . >>> df.flags.allows_duplicate_labels True >>> df.flags.allows_duplicate_labels = False Or by slicing with a key >>> df.flags["allows_duplicate_labels"] False >>> df.flags["allows_duplicate_labels"] = True
pandas.reference.api.pandas.series.flags
pandas.Series.floordiv Series.floordiv(other, level=None, fill_value=None, axis=0)[source] Return Integer division of series and other, element-wise (binary operator floordiv). Equivalent to series // other, but with support to substitute a fill_value for missing data in either one of the inputs. Parameters other:Series or scalar value fill_value:None or float value, default None (NaN) Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing. level:int or name Broadcast across a level, matching Index values on the passed MultiIndex level. Returns Series The result of the operation. See also Series.rfloordiv Reverse of the Integer division operator, see Python documentation for more details. Examples >>> a = pd.Series([1, 1, 1, np.nan], index=['a', 'b', 'c', 'd']) >>> a a 1.0 b 1.0 c 1.0 d NaN dtype: float64 >>> b = pd.Series([1, np.nan, 1, np.nan], index=['a', 'b', 'd', 'e']) >>> b a 1.0 b NaN d 1.0 e NaN dtype: float64 >>> a.floordiv(b, fill_value=0) a 1.0 b NaN c NaN d 0.0 e NaN dtype: float64
pandas.reference.api.pandas.series.floordiv
pandas.Series.ge Series.ge(other, level=None, fill_value=None, axis=0)[source] Return Greater than or equal to of series and other, element-wise (binary operator ge). Equivalent to series >= other, but with support to substitute a fill_value for missing data in either one of the inputs. Parameters other:Series or scalar value fill_value:None or float value, default None (NaN) Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing. level:int or name Broadcast across a level, matching Index values on the passed MultiIndex level. Returns Series The result of the operation. Examples >>> a = pd.Series([1, 1, 1, np.nan, 1], index=['a', 'b', 'c', 'd', 'e']) >>> a a 1.0 b 1.0 c 1.0 d NaN e 1.0 dtype: float64 >>> b = pd.Series([0, 1, 2, np.nan, 1], index=['a', 'b', 'c', 'd', 'f']) >>> b a 0.0 b 1.0 c 2.0 d NaN f 1.0 dtype: float64 >>> a.ge(b, fill_value=0) a True b True c False d False e True f False dtype: bool
pandas.reference.api.pandas.series.ge
pandas.Series.get Series.get(key, default=None)[source] Get item from object for given key (ex: DataFrame column). Returns default value if not found. Parameters key:object Returns value:same type as items contained in object Examples >>> df = pd.DataFrame( ... [ ... [24.3, 75.7, "high"], ... [31, 87.8, "high"], ... [22, 71.6, "medium"], ... [35, 95, "medium"], ... ], ... columns=["temp_celsius", "temp_fahrenheit", "windspeed"], ... index=pd.date_range(start="2014-02-12", end="2014-02-15", freq="D"), ... ) >>> df temp_celsius temp_fahrenheit windspeed 2014-02-12 24.3 75.7 high 2014-02-13 31.0 87.8 high 2014-02-14 22.0 71.6 medium 2014-02-15 35.0 95.0 medium >>> df.get(["temp_celsius", "windspeed"]) temp_celsius windspeed 2014-02-12 24.3 high 2014-02-13 31.0 high 2014-02-14 22.0 medium 2014-02-15 35.0 medium If the key isn’t found, the default value will be used. >>> df.get(["temp_celsius", "temp_kelvin"], default="default_value") 'default_value'
pandas.reference.api.pandas.series.get
pandas.Series.groupby Series.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=NoDefault.no_default, observed=False, dropna=True)[source] Group Series using a mapper or by a Series of columns. A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups. Parameters by:mapping, function, label, or list of labels Used to determine the groups for the groupby. If by is a function, it’s called on each value of the object’s index. If a dict or Series is passed, the Series or dict VALUES will be used to determine the groups (the Series’ values are first aligned; see .align() method). If a list or ndarray of length equal to the selected axis is passed (see the groupby user guide), the values are used as-is to determine the groups. A label or list of labels may be passed to group by the columns in self. Notice that a tuple is interpreted as a (single) key. axis:{0 or ‘index’, 1 or ‘columns’}, default 0 Split along rows (0) or columns (1). level:int, level name, or sequence of such, default None If the axis is a MultiIndex (hierarchical), group by a particular level or levels. as_index:bool, default True For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output. sort:bool, default True Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. Groupby preserves the order of rows within each group. group_keys:bool, default True When calling apply, add group keys to index to identify pieces. squeeze:bool, default False Reduce the dimensionality of the return type if possible, otherwise return a consistent type. Deprecated since version 1.1.0. observed:bool, default False This only applies if any of the groupers are Categoricals. If True: only show observed values for categorical groupers. If False: show all values for categorical groupers. dropna:bool, default True If True, and if group keys contain NA values, NA values together with row/column will be dropped. If False, NA values will also be treated as the key in groups. New in version 1.1.0. Returns SeriesGroupBy Returns a groupby object that contains information about the groups. See also resample Convenience method for frequency conversion and resampling of time series. Notes See the user guide for more detailed usage and examples, including splitting an object into groups, iterating through groups, selecting a group, aggregation, and more. Examples >>> ser = pd.Series([390., 350., 30., 20.], ... index=['Falcon', 'Falcon', 'Parrot', 'Parrot'], name="Max Speed") >>> ser Falcon 390.0 Falcon 350.0 Parrot 30.0 Parrot 20.0 Name: Max Speed, dtype: float64 >>> ser.groupby(["a", "b", "a", "b"]).mean() a 210.0 b 185.0 Name: Max Speed, dtype: float64 >>> ser.groupby(level=0).mean() Falcon 370.0 Parrot 25.0 Name: Max Speed, dtype: float64 >>> ser.groupby(ser > 100).mean() Max Speed False 25.0 True 370.0 Name: Max Speed, dtype: float64 Grouping by Indexes We can groupby different levels of a hierarchical index using the level parameter: >>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'], ... ['Captive', 'Wild', 'Captive', 'Wild']] >>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type')) >>> ser = pd.Series([390., 350., 30., 20.], index=index, name="Max Speed") >>> ser Animal Type Falcon Captive 390.0 Wild 350.0 Parrot Captive 30.0 Wild 20.0 Name: Max Speed, dtype: float64 >>> ser.groupby(level=0).mean() Animal Falcon 370.0 Parrot 25.0 Name: Max Speed, dtype: float64 >>> ser.groupby(level="Type").mean() Type Captive 210.0 Wild 185.0 Name: Max Speed, dtype: float64 We can also choose to include NA in group keys or not by defining dropna parameter, the default setting is True. >>> ser = pd.Series([1, 2, 3, 3], index=["a", 'a', 'b', np.nan]) >>> ser.groupby(level=0).sum() a 3 b 3 dtype: int64 >>> ser.groupby(level=0, dropna=False).sum() a 3 b 3 NaN 3 dtype: int64 >>> arrays = ['Falcon', 'Falcon', 'Parrot', 'Parrot'] >>> ser = pd.Series([390., 350., 30., 20.], index=arrays, name="Max Speed") >>> ser.groupby(["a", "b", "a", np.nan]).mean() a 210.0 b 350.0 Name: Max Speed, dtype: float64 >>> ser.groupby(["a", "b", "a", np.nan], dropna=False).mean() a 210.0 b 350.0 NaN 20.0 Name: Max Speed, dtype: float64
pandas.reference.api.pandas.series.groupby
pandas.Series.gt Series.gt(other, level=None, fill_value=None, axis=0)[source] Return Greater than of series and other, element-wise (binary operator gt). Equivalent to series > other, but with support to substitute a fill_value for missing data in either one of the inputs. Parameters other:Series or scalar value fill_value:None or float value, default None (NaN) Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing. level:int or name Broadcast across a level, matching Index values on the passed MultiIndex level. Returns Series The result of the operation. Examples >>> a = pd.Series([1, 1, 1, np.nan, 1], index=['a', 'b', 'c', 'd', 'e']) >>> a a 1.0 b 1.0 c 1.0 d NaN e 1.0 dtype: float64 >>> b = pd.Series([0, 1, 2, np.nan, 1], index=['a', 'b', 'c', 'd', 'f']) >>> b a 0.0 b 1.0 c 2.0 d NaN f 1.0 dtype: float64 >>> a.gt(b, fill_value=0) a True b False c False d False e True f False dtype: bool
pandas.reference.api.pandas.series.gt
pandas.Series.hasnans propertySeries.hasnans Return True if there are any NaNs. Enables various performance speedups.
pandas.reference.api.pandas.series.hasnans
pandas.Series.head Series.head(n=5)[source] Return the first n rows. This function returns the first n rows for the object based on position. It is useful for quickly testing if your object has the right type of data in it. For negative values of n, this function returns all rows except the last n rows, equivalent to df[:-n]. Parameters n:int, 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
pandas.reference.api.pandas.series.head
pandas.Series.hist Series.hist(by=None, ax=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, figsize=None, bins=10, backend=None, legend=False, **kwargs)[source] Draw histogram of the input series using matplotlib. Parameters by:object, optional If passed, then used to form histograms for separate groups. ax:matplotlib axis object If not passed, uses gca(). grid:bool, default True Whether to show axis grid lines. xlabelsize:int, default None If specified changes the x-axis label size. xrot:float, default None Rotation of x axis labels. ylabelsize:int, default None If specified changes the y-axis label size. yrot:float, default None Rotation of y axis labels. figsize:tuple, default None Figure size in inches by default. bins:int or sequence, default 10 Number of histogram bins to be used. If an integer is given, bins + 1 bin edges are calculated and returned. If bins is a sequence, gives bin edges, including left edge of first bin and right edge of last bin. In this case, bins is returned unmodified. backend:str, default None Backend to use instead of the backend specified in the option plotting.backend. For instance, ‘matplotlib’. Alternatively, to specify the plotting.backend for the whole session, set pd.options.plotting.backend. New in version 1.0.0. legend:bool, default False Whether to show the legend. New in version 1.1.0. **kwargs To be passed to the actual plotting function. Returns matplotlib.AxesSubplot A histogram plot. See also matplotlib.axes.Axes.hist Plot a histogram using matplotlib.
pandas.reference.api.pandas.series.hist
pandas.Series.iat propertySeries.iat Access a single value for a row/column pair by integer position. Similar to iloc, in that both provide integer-based lookups. Use iat if 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] 1 Set value at specified row/column pair >>> df.iat[1, 2] = 10 >>> df.iat[1, 2] 10 Get value within a series >>> df.loc[0].iat[1] 2
pandas.reference.api.pandas.series.iat
pandas.Series.idxmax Series.idxmax(axis=0, skipna=True, *args, **kwargs)[source] Return the row label of the maximum value. If multiple values equal the maximum, the first row label with that value is returned. Parameters axis:int, default 0 For compatibility with DataFrame.idxmax. Redundant for application on Series. skipna:bool, default True Exclude NA/null values. If the entire Series is NA, the result will be NA. *args, **kwargs Additional arguments and keywords have no effect but might be accepted for compatibility with NumPy. Returns Index Label of the maximum value. Raises ValueError If the Series is empty. See also numpy.argmax Return indices of the maximum values along the given axis. DataFrame.idxmax Return index of first occurrence of maximum over requested axis. Series.idxmin Return index label of the first occurrence of minimum of values. Notes This method is the Series version of ndarray.argmax. This method returns the label of the maximum, while ndarray.argmax returns the position. To get the position, use series.values.argmax(). Examples >>> s = pd.Series(data=[1, None, 4, 3, 4], ... index=['A', 'B', 'C', 'D', 'E']) >>> s A 1.0 B NaN C 4.0 D 3.0 E 4.0 dtype: float64 >>> s.idxmax() 'C' If skipna is False and there is an NA value in the data, the function returns nan. >>> s.idxmax(skipna=False) nan
pandas.reference.api.pandas.series.idxmax
pandas.Series.idxmin Series.idxmin(axis=0, skipna=True, *args, **kwargs)[source] Return the row label of the minimum value. If multiple values equal the minimum, the first row label with that value is returned. Parameters axis:int, default 0 For compatibility with DataFrame.idxmin. Redundant for application on Series. skipna:bool, default True Exclude NA/null values. If the entire Series is NA, the result will be NA. *args, **kwargs Additional arguments and keywords have no effect but might be accepted for compatibility with NumPy. Returns Index Label of the minimum value. Raises ValueError If the Series is empty. See also numpy.argmin Return indices of the minimum values along the given axis. DataFrame.idxmin Return index of first occurrence of minimum over requested axis. Series.idxmax Return index label of the first occurrence of maximum of values. Notes This method is the Series version of ndarray.argmin. This method returns the label of the minimum, while ndarray.argmin returns the position. To get the position, use series.values.argmin(). Examples >>> s = pd.Series(data=[1, None, 4, 1], ... index=['A', 'B', 'C', 'D']) >>> s A 1.0 B NaN C 4.0 D 1.0 dtype: float64 >>> s.idxmin() 'A' If skipna is False and there is an NA value in the data, the function returns nan. >>> s.idxmin(skipna=False) nan
pandas.reference.api.pandas.series.idxmin
pandas.Series.iloc propertySeries.iloc Purely integer-location based indexing for selection by position. .iloc[] is primarily integer position based (from 0 to length-1 of 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 callable function 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. .iloc will raise IndexError if 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.core.series.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.core.frame.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 lambda is 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] 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
pandas.reference.api.pandas.series.iloc
pandas.Series.index Series.index The index (axis labels) of the Series.
pandas.reference.api.pandas.series.index
pandas.Series.infer_objects Series.infer_objects()[source] Attempt to infer better dtypes for object columns. Attempts soft conversion of object-dtyped columns, leaving non-object and unconvertible columns unchanged. The inference rules are the same as during normal Series/DataFrame construction. Returns converted:same type as input object See also to_datetime Convert argument to datetime. to_timedelta Convert argument to timedelta. to_numeric Convert argument to numeric type. convert_dtypes Convert argument to best possible dtype. Examples >>> df = pd.DataFrame({"A": ["a", 1, 2, 3]}) >>> df = df.iloc[1:] >>> df A 1 1 2 2 3 3 >>> df.dtypes A object dtype: object >>> df.infer_objects().dtypes A int64 dtype: object
pandas.reference.api.pandas.series.infer_objects
pandas.Series.info Series.info(verbose=None, buf=None, max_cols=None, memory_usage=None, show_counts=True)[source] Print a concise summary of a Series. This method prints information about a Series including the index dtype, non-null values and memory usage. New in version 1.4.0. Parameters data:Series Series to print information about. verbose:bool, optional Whether to print the full summary. By default, the setting in pandas.options.display.max_info_columns is followed. buf:writable buffer, defaults to sys.stdout Where to send the output. By default, the output is printed to sys.stdout. Pass a writable buffer if you need to further process the output. memory_usage:bool, str, optional Specifies whether total memory usage of the Series elements (including the index) should be displayed. By default, this follows the pandas.options.display.memory_usage setting. True always show memory usage. False never shows memory usage. A value of ‘deep’ is equivalent to “True with deep introspection”. Memory usage is shown in human-readable units (base-2 representation). Without deep introspection a memory estimation is made based in column dtype and number of rows assuming values consume the same memory amount for corresponding dtypes. With deep memory introspection, a real memory usage calculation is performed at the cost of computational resources. show_counts:bool, optional Whether to show the non-null counts. By default, this is shown only if the DataFrame is smaller than pandas.options.display.max_info_rows and pandas.options.display.max_info_columns. A value of True always shows the counts, and False never shows the counts. Returns None This method prints a summary of a Series and returns None. See also Series.describe Generate descriptive statistics of Series. Series.memory_usage Memory usage of Series. Examples >>> int_values = [1, 2, 3, 4, 5] >>> text_values = ['alpha', 'beta', 'gamma', 'delta', 'epsilon'] >>> s = pd.Series(text_values, index=int_values) >>> s.info() <class 'pandas.core.series.Series'> Int64Index: 5 entries, 1 to 5 Series name: None Non-Null Count Dtype -------------- ----- 5 non-null object dtypes: object(1) memory usage: 80.0+ bytes Prints a summary excluding information about its values: >>> s.info(verbose=False) <class 'pandas.core.series.Series'> Int64Index: 5 entries, 1 to 5 dtypes: object(1) memory usage: 80.0+ bytes Pipe output of Series.info to buffer instead of sys.stdout, get buffer content and writes to a text file: >>> import io >>> buffer = io.StringIO() >>> s.info(buf=buffer) >>> s = buffer.getvalue() >>> with open("df_info.txt", "w", ... encoding="utf-8") as f: ... f.write(s) 260 The memory_usage parameter allows deep introspection mode, specially useful for big Series and fine-tune memory optimization: >>> random_strings_array = np.random.choice(['a', 'b', 'c'], 10 ** 6) >>> s = pd.Series(np.random.choice(['a', 'b', 'c'], 10 ** 6)) >>> s.info() <class 'pandas.core.series.Series'> RangeIndex: 1000000 entries, 0 to 999999 Series name: None Non-Null Count Dtype -------------- ----- 1000000 non-null object dtypes: object(1) memory usage: 7.6+ MB >>> s.info(memory_usage='deep') <class 'pandas.core.series.Series'> RangeIndex: 1000000 entries, 0 to 999999 Series name: None Non-Null Count Dtype -------------- ----- 1000000 non-null object dtypes: object(1) memory usage: 55.3 MB
pandas.reference.api.pandas.series.info
pandas.Series.interpolate Series.interpolate(method='linear', axis=0, limit=None, inplace=False, limit_direction=None, limit_area=None, downcast=None, **kwargs)[source] Fill NaN values using an interpolation method. Please note that only method='linear' is supported for DataFrame/Series with a MultiIndex. Parameters method:str, default ‘linear’ Interpolation technique to use. One of: ‘linear’: Ignore the index and treat the values as equally spaced. This is the only method supported on MultiIndexes. ‘time’: Works on daily and higher resolution data to interpolate given length of interval. ‘index’, ‘values’: use the actual numerical values of the index. ‘pad’: Fill in NaNs using existing values. ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’, ‘spline’, ‘barycentric’, ‘polynomial’: Passed to scipy.interpolate.interp1d. These methods use the numerical values of the index. Both ‘polynomial’ and ‘spline’ require that you also specify an order (int), e.g. df.interpolate(method='polynomial', order=5). ‘krogh’, ‘piecewise_polynomial’, ‘spline’, ‘pchip’, ‘akima’, ‘cubicspline’: Wrappers around the SciPy interpolation methods of similar names. See Notes. ‘from_derivatives’: Refers to scipy.interpolate.BPoly.from_derivatives which replaces ‘piecewise_polynomial’ interpolation method in scipy 0.18. axis:{{0 or ‘index’, 1 or ‘columns’, None}}, default None Axis to interpolate along. limit:int, optional Maximum number of consecutive NaNs to fill. Must be greater than 0. inplace:bool, default False Update the data in place if possible. limit_direction:{{‘forward’, ‘backward’, ‘both’}}, Optional Consecutive NaNs will be filled in this direction. If limit is specified: If ‘method’ is ‘pad’ or ‘ffill’, ‘limit_direction’ must be ‘forward’. If ‘method’ is ‘backfill’ or ‘bfill’, ‘limit_direction’ must be ‘backwards’. If ‘limit’ is not specified: If ‘method’ is ‘backfill’ or ‘bfill’, the default is ‘backward’ else the default is ‘forward’ Changed in version 1.1.0: raises ValueError if limit_direction is ‘forward’ or ‘both’ and method is ‘backfill’ or ‘bfill’. raises ValueError if limit_direction is ‘backward’ or ‘both’ and method is ‘pad’ or ‘ffill’. limit_area:{{None, ‘inside’, ‘outside’}}, default None If limit is specified, consecutive NaNs will be filled with this restriction. None: No fill restriction. ‘inside’: Only fill NaNs surrounded by valid values (interpolate). ‘outside’: Only fill NaNs outside valid values (extrapolate). downcast:optional, ‘infer’ or None, defaults to None Downcast dtypes if possible. ``**kwargs``:optional Keyword arguments to pass on to the interpolating function. Returns Series or DataFrame or None Returns the same object type as the caller, interpolated at some or all NaN values or None if inplace=True. See also fillna Fill missing values using different methods. scipy.interpolate.Akima1DInterpolator Piecewise cubic polynomials (Akima interpolator). scipy.interpolate.BPoly.from_derivatives Piecewise polynomial in the Bernstein basis. scipy.interpolate.interp1d Interpolate a 1-D function. scipy.interpolate.KroghInterpolator Interpolate polynomial (Krogh interpolator). scipy.interpolate.PchipInterpolator PCHIP 1-d monotonic cubic interpolation. scipy.interpolate.CubicSpline Cubic spline data interpolator. Notes The ‘krogh’, ‘piecewise_polynomial’, ‘spline’, ‘pchip’ and ‘akima’ methods are wrappers around the respective SciPy implementations of similar names. These use the actual numerical values of the index. For more information on their behavior, see the SciPy documentation and SciPy tutorial. Examples Filling in NaN in a Series via linear interpolation. >>> s = pd.Series([0, 1, np.nan, 3]) >>> s 0 0.0 1 1.0 2 NaN 3 3.0 dtype: float64 >>> s.interpolate() 0 0.0 1 1.0 2 2.0 3 3.0 dtype: float64 Filling in NaN in a Series by padding, but filling at most two consecutive NaN at a time. >>> s = pd.Series([np.nan, "single_one", np.nan, ... "fill_two_more", np.nan, np.nan, np.nan, ... 4.71, np.nan]) >>> s 0 NaN 1 single_one 2 NaN 3 fill_two_more 4 NaN 5 NaN 6 NaN 7 4.71 8 NaN dtype: object >>> s.interpolate(method='pad', limit=2) 0 NaN 1 single_one 2 single_one 3 fill_two_more 4 fill_two_more 5 fill_two_more 6 NaN 7 4.71 8 4.71 dtype: object Filling in NaN in a Series via polynomial interpolation or splines: Both ‘polynomial’ and ‘spline’ methods require that you also specify an order (int). >>> s = pd.Series([0, 2, np.nan, 8]) >>> s.interpolate(method='polynomial', order=2) 0 0.000000 1 2.000000 2 4.666667 3 8.000000 dtype: float64 Fill the DataFrame forward (that is, going down) along each column using linear interpolation. Note how the last entry in column ‘a’ is interpolated differently, because there is no entry after it to use for interpolation. Note how the first entry in column ‘b’ remains NaN, because there is no entry before it to use for interpolation. >>> df = pd.DataFrame([(0.0, np.nan, -1.0, 1.0), ... (np.nan, 2.0, np.nan, np.nan), ... (2.0, 3.0, np.nan, 9.0), ... (np.nan, 4.0, -4.0, 16.0)], ... columns=list('abcd')) >>> df a b c d 0 0.0 NaN -1.0 1.0 1 NaN 2.0 NaN NaN 2 2.0 3.0 NaN 9.0 3 NaN 4.0 -4.0 16.0 >>> df.interpolate(method='linear', limit_direction='forward', axis=0) a b c d 0 0.0 NaN -1.0 1.0 1 1.0 2.0 -2.0 5.0 2 2.0 3.0 -3.0 9.0 3 2.0 4.0 -4.0 16.0 Using polynomial interpolation. >>> df['d'].interpolate(method='polynomial', order=2) 0 1.0 1 4.0 2 9.0 3 16.0 Name: d, dtype: float64
pandas.reference.api.pandas.series.interpolate
pandas.Series.is_monotonic propertySeries.is_monotonic Return boolean if values in the object are monotonic_increasing. Returns bool
pandas.reference.api.pandas.series.is_monotonic
pandas.Series.is_monotonic_decreasing propertySeries.is_monotonic_decreasing Return boolean if values in the object are monotonic_decreasing. Returns bool
pandas.reference.api.pandas.series.is_monotonic_decreasing
pandas.Series.is_monotonic_increasing propertySeries.is_monotonic_increasing Alias for is_monotonic.
pandas.reference.api.pandas.series.is_monotonic_increasing
pandas.Series.is_unique propertySeries.is_unique Return boolean if values in the object are unique. Returns bool
pandas.reference.api.pandas.series.is_unique
pandas.Series.isin Series.isin(values)[source] Whether elements in Series are contained in values. Return a boolean Series showing whether each element in the Series matches an element in the passed sequence of values exactly. Parameters values:set or list-like The sequence of values to test. Passing in a single string will raise a TypeError. Instead, turn a single string into a list of one element. Returns Series Series of booleans indicating if each element is in values. Raises TypeError If values is a string See also DataFrame.isin Equivalent method on DataFrame. Examples >>> s = pd.Series(['lama', 'cow', 'lama', 'beetle', 'lama', ... 'hippo'], name='animal') >>> s.isin(['cow', 'lama']) 0 True 1 True 2 True 3 False 4 True 5 False Name: animal, dtype: bool To invert the boolean values, use the ~ operator: >>> ~s.isin(['cow', 'lama']) 0 False 1 False 2 False 3 True 4 False 5 True Name: animal, dtype: bool Passing a single string as s.isin('lama') will raise an error. Use a list of one element instead: >>> s.isin(['lama']) 0 True 1 False 2 True 3 False 4 True 5 False Name: animal, dtype: bool Strings and integers are distinct and are therefore not comparable: >>> pd.Series([1]).isin(['1']) 0 False dtype: bool >>> pd.Series([1.1]).isin(['1.1']) 0 False dtype: bool
pandas.reference.api.pandas.series.isin
pandas.Series.isna Series.isna()[source] Detect missing values. Return a boolean same-sized object indicating if the values are NA. NA values, such as None or numpy.NaN, gets mapped to True values. Everything else gets mapped to False values. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). Returns Series Mask of bool values for each element in Series that indicates whether an element is an NA value. See also Series.isnull Alias of isna. Series.notna Boolean inverse of isna. Series.dropna Omit axes labels with missing values. isna Top-level isna. Examples Show which entries in a DataFrame are NA. >>> df = pd.DataFrame(dict(age=[5, 6, np.NaN], ... born=[pd.NaT, pd.Timestamp('1939-05-27'), ... pd.Timestamp('1940-04-25')], ... name=['Alfred', 'Batman', ''], ... toy=[None, 'Batmobile', 'Joker'])) >>> df age born name toy 0 5.0 NaT Alfred None 1 6.0 1939-05-27 Batman Batmobile 2 NaN 1940-04-25 Joker >>> df.isna() age born name toy 0 False True False True 1 False False False False 2 True False False False Show which entries in a Series are NA. >>> ser = pd.Series([5, 6, np.NaN]) >>> ser 0 5.0 1 6.0 2 NaN dtype: float64 >>> ser.isna() 0 False 1 False 2 True dtype: bool
pandas.reference.api.pandas.series.isna
pandas.Series.isnull Series.isnull()[source] Series.isnull is an alias for Series.isna. Detect missing values. Return a boolean same-sized object indicating if the values are NA. NA values, such as None or numpy.NaN, gets mapped to True values. Everything else gets mapped to False values. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). Returns Series Mask of bool values for each element in Series that indicates whether an element is an NA value. See also Series.isnull Alias of isna. Series.notna Boolean inverse of isna. Series.dropna Omit axes labels with missing values. isna Top-level isna. Examples Show which entries in a DataFrame are NA. >>> df = pd.DataFrame(dict(age=[5, 6, np.NaN], ... born=[pd.NaT, pd.Timestamp('1939-05-27'), ... pd.Timestamp('1940-04-25')], ... name=['Alfred', 'Batman', ''], ... toy=[None, 'Batmobile', 'Joker'])) >>> df age born name toy 0 5.0 NaT Alfred None 1 6.0 1939-05-27 Batman Batmobile 2 NaN 1940-04-25 Joker >>> df.isna() age born name toy 0 False True False True 1 False False False False 2 True False False False Show which entries in a Series are NA. >>> ser = pd.Series([5, 6, np.NaN]) >>> ser 0 5.0 1 6.0 2 NaN dtype: float64 >>> ser.isna() 0 False 1 False 2 True dtype: bool
pandas.reference.api.pandas.series.isnull
pandas.Series.item Series.item()[source] Return the first element of the underlying data as a Python scalar. Returns scalar The first element of %(klass)s. Raises ValueError If the data is not length-1.
pandas.reference.api.pandas.series.item
pandas.Series.items Series.items()[source] Lazily iterate over (index, value) tuples. This method returns an iterable tuple (index, value). This is convenient if you want to create a lazy iterator. Returns iterable Iterable of tuples containing the (index, value) pairs from a Series. See also DataFrame.items Iterate over (column name, Series) pairs. DataFrame.iterrows Iterate over DataFrame rows as (index, Series) pairs. Examples >>> s = pd.Series(['A', 'B', 'C']) >>> for index, value in s.items(): ... print(f"Index : {index}, Value : {value}") Index : 0, Value : A Index : 1, Value : B Index : 2, Value : C
pandas.reference.api.pandas.series.items
pandas.Series.iteritems Series.iteritems()[source] Lazily iterate over (index, value) tuples. This method returns an iterable tuple (index, value). This is convenient if you want to create a lazy iterator. Returns iterable Iterable of tuples containing the (index, value) pairs from a Series. See also DataFrame.items Iterate over (column name, Series) pairs. DataFrame.iterrows Iterate over DataFrame rows as (index, Series) pairs. Examples >>> s = pd.Series(['A', 'B', 'C']) >>> for index, value in s.items(): ... print(f"Index : {index}, Value : {value}") Index : 0, Value : A Index : 1, Value : B Index : 2, Value : C
pandas.reference.api.pandas.series.iteritems
pandas.Series.keys Series.keys()[source] Return alias for index. Returns Index Index of the Series.
pandas.reference.api.pandas.series.keys
pandas.Series.kurt Series.kurt(axis=NoDefault.no_default, skipna=True, level=None, numeric_only=None, **kwargs)[source] Return unbiased kurtosis over requested axis. Kurtosis obtained using Fisher’s definition of kurtosis (kurtosis of normal == 0.0). Normalized by N-1. Parameters axis:{index (0)} Axis for the function to be applied on. skipna:bool, default True Exclude NA/null values when computing the result. level:int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar. numeric_only:bool, default None Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. **kwargs Additional keyword arguments to be passed to the function. Returns scalar or Series (if level specified)
pandas.reference.api.pandas.series.kurt
pandas.Series.kurtosis Series.kurtosis(axis=NoDefault.no_default, skipna=True, level=None, numeric_only=None, **kwargs)[source] Return unbiased kurtosis over requested axis. Kurtosis obtained using Fisher’s definition of kurtosis (kurtosis of normal == 0.0). Normalized by N-1. Parameters axis:{index (0)} Axis for the function to be applied on. skipna:bool, default True Exclude NA/null values when computing the result. level:int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar. numeric_only:bool, default None Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. **kwargs Additional keyword arguments to be passed to the function. Returns scalar or Series (if level specified)
pandas.reference.api.pandas.series.kurtosis
pandas.Series.last Series.last(offset)[source] Select final periods of time series data based on a date offset. For a DataFrame with a sorted DatetimeIndex, this function selects the last few rows based on a date offset. Parameters offset:str, DateOffset, dateutil.relativedelta The offset length of the data that will be selected. For instance, ‘3D’ will display all the rows having their index within the last 3 days. Returns Series or DataFrame A subset of the caller. Raises TypeError If the index is not a DatetimeIndex See also first Select initial periods of time series based on a date offset. at_time Select values at a particular time of the day. between_time Select values between particular times of the day. Examples >>> i = pd.date_range('2018-04-09', periods=4, freq='2D') >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i) >>> ts A 2018-04-09 1 2018-04-11 2 2018-04-13 3 2018-04-15 4 Get the rows for the last 3 days: >>> ts.last('3D') A 2018-04-13 3 2018-04-15 4 Notice the data for 3 last calendar days were returned, not the last 3 observed days in the dataset, and therefore data for 2018-04-11 was not returned.
pandas.reference.api.pandas.series.last
pandas.Series.last_valid_index Series.last_valid_index()[source] Return index for last non-NA value or None, if no NA value is found. Returns scalar:type of index Notes If all elements are non-NA/null, returns None. Also returns None for empty Series/DataFrame.
pandas.reference.api.pandas.series.last_valid_index
pandas.Series.le Series.le(other, level=None, fill_value=None, axis=0)[source] Return Less than or equal to of series and other, element-wise (binary operator le). Equivalent to series <= other, but with support to substitute a fill_value for missing data in either one of the inputs. Parameters other:Series or scalar value fill_value:None or float value, default None (NaN) Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing. level:int or name Broadcast across a level, matching Index values on the passed MultiIndex level. Returns Series The result of the operation. Examples >>> a = pd.Series([1, 1, 1, np.nan, 1], index=['a', 'b', 'c', 'd', 'e']) >>> a a 1.0 b 1.0 c 1.0 d NaN e 1.0 dtype: float64 >>> b = pd.Series([0, 1, 2, np.nan, 1], index=['a', 'b', 'c', 'd', 'f']) >>> b a 0.0 b 1.0 c 2.0 d NaN f 1.0 dtype: float64 >>> a.le(b, fill_value=0) a False b True c True d False e False f True dtype: bool
pandas.reference.api.pandas.series.le
pandas.Series.loc propertySeries.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. 5 or 'a', (note that 5 is 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 callable function 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'] 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 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 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'] 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
pandas.reference.api.pandas.series.loc
pandas.Series.lt Series.lt(other, level=None, fill_value=None, axis=0)[source] Return Less than of series and other, element-wise (binary operator lt). Equivalent to series < other, but with support to substitute a fill_value for missing data in either one of the inputs. Parameters other:Series or scalar value fill_value:None or float value, default None (NaN) Fill existing missing (NaN) values, and any new element needed for successful Series alignment, with this value before computation. If data in both corresponding Series locations is missing the result of filling (at that location) will be missing. level:int or name Broadcast across a level, matching Index values on the passed MultiIndex level. Returns Series The result of the operation. Examples >>> a = pd.Series([1, 1, 1, np.nan, 1], index=['a', 'b', 'c', 'd', 'e']) >>> a a 1.0 b 1.0 c 1.0 d NaN e 1.0 dtype: float64 >>> b = pd.Series([0, 1, 2, np.nan, 1], index=['a', 'b', 'c', 'd', 'f']) >>> b a 0.0 b 1.0 c 2.0 d NaN f 1.0 dtype: float64 >>> a.lt(b, fill_value=0) a False b False c True d False e False f True dtype: bool
pandas.reference.api.pandas.series.lt
pandas.Series.mad Series.mad(axis=None, skipna=True, level=None)[source] Return the mean absolute deviation of the values over the requested axis. Parameters axis:{index (0)} Axis for the function to be applied on. skipna:bool, default True Exclude NA/null values when computing the result. level:int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar. Returns scalar or Series (if level specified)
pandas.reference.api.pandas.series.mad
pandas.Series.map Series.map(arg, na_action=None)[source] Map values of Series according to an input mapping or function. Used for substituting each value in a Series with another value, that may be derived from a function, a dict or a Series. Parameters arg:function, collections.abc.Mapping subclass or Series Mapping correspondence. na_action:{None, ‘ignore’}, default None If ‘ignore’, propagate NaN values, without passing them to the mapping correspondence. Returns Series Same index as caller. See also Series.apply For applying more complex functions on a Series. DataFrame.apply Apply a function row-/column-wise. DataFrame.applymap Apply a function elementwise on a whole DataFrame. Notes When arg is a dictionary, values in Series that are not in the dictionary (as keys) are converted to NaN. However, if the dictionary is a dict subclass that defines __missing__ (i.e. provides a method for default values), then this default is used rather than NaN. Examples >>> s = pd.Series(['cat', 'dog', np.nan, 'rabbit']) >>> s 0 cat 1 dog 2 NaN 3 rabbit dtype: object map accepts a dict or a Series. Values that are not found in the dict are converted to NaN, unless the dict has a default value (e.g. defaultdict): >>> s.map({'cat': 'kitten', 'dog': 'puppy'}) 0 kitten 1 puppy 2 NaN 3 NaN dtype: object It also accepts a function: >>> s.map('I am a {}'.format) 0 I am a cat 1 I am a dog 2 I am a nan 3 I am a rabbit dtype: object To avoid applying the function to missing values (and keep them as NaN) na_action='ignore' can be used: >>> s.map('I am a {}'.format, na_action='ignore') 0 I am a cat 1 I am a dog 2 NaN 3 I am a rabbit dtype: object
pandas.reference.api.pandas.series.map
pandas.Series.mask Series.mask(cond, other=nan, inplace=False, axis=None, level=None, errors=NoDefault.no_default, try_cast=NoDefault.no_default)[source] Replace values where the condition is True. Parameters cond:bool Series/DataFrame, array-like, or callable Where cond is False, keep the original value. Where True, replace with corresponding value from other. If cond is callable, it is computed on the Series/DataFrame and should return boolean Series/DataFrame or array. The callable must not change input Series/DataFrame (though pandas doesn’t check it). other:scalar, Series/DataFrame, or callable Entries where cond is True are replaced with corresponding value from other. If other is callable, it is computed on the Series/DataFrame and should return scalar or Series/DataFrame. The callable must not change input Series/DataFrame (though pandas doesn’t check it). inplace:bool, default False Whether to perform the operation in place on the data. axis:int, default None Alignment axis if needed. level:int, default None Alignment level if needed. errors:str, {‘raise’, ‘ignore’}, default ‘raise’ Note that currently this parameter won’t affect the results and will always coerce to a suitable dtype. ‘raise’ : allow exceptions to be raised. ‘ignore’ : suppress exceptions. On error return original object. try_cast:bool, default None Try to cast the result back to the input type (if possible). Deprecated since version 1.3.0: Manually cast back if necessary. Returns Same type as caller or None if inplace=True. See also DataFrame.where() Return an object of same shape as self. Notes The mask method is an application of the if-then idiom. For each element in the calling DataFrame, if cond is False the element is used; otherwise the corresponding element from the DataFrame other is used. The signature for DataFrame.where() differs from numpy.where(). Roughly df1.where(m, df2) is equivalent to np.where(m, df1, df2). For further details and examples see the mask documentation in indexing. Examples >>> s = pd.Series(range(5)) >>> s.where(s > 0) 0 NaN 1 1.0 2 2.0 3 3.0 4 4.0 dtype: float64 >>> s.mask(s > 0) 0 0.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 >>> s.where(s > 1, 10) 0 10 1 10 2 2 3 3 4 4 dtype: int64 >>> s.mask(s > 1, 10) 0 0 1 1 2 10 3 10 4 10 dtype: int64 >>> df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B']) >>> df A B 0 0 1 1 2 3 2 4 5 3 6 7 4 8 9 >>> m = df % 3 == 0 >>> df.where(m, -df) A B 0 0 -1 1 -2 3 2 -4 -5 3 6 -7 4 -8 9 >>> df.where(m, -df) == np.where(m, df, -df) A B 0 True True 1 True True 2 True True 3 True True 4 True True >>> df.where(m, -df) == df.mask(~m, -df) A B 0 True True 1 True True 2 True True 3 True True 4 True True
pandas.reference.api.pandas.series.mask
pandas.Series.max Series.max(axis=NoDefault.no_default, skipna=True, level=None, numeric_only=None, **kwargs)[source] Return the maximum of the values over the requested axis. If you want the index of the maximum, use idxmax. This is the equivalent of the numpy.ndarray method argmax. Parameters axis:{index (0)} Axis for the function to be applied on. skipna:bool, default True Exclude NA/null values when computing the result. level:int or level name, default None If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar. numeric_only:bool, default None Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. **kwargs Additional keyword arguments to be passed to the function. Returns scalar or Series (if level specified) See also Series.sum Return the sum. Series.min Return the minimum. Series.max Return the maximum. Series.idxmin Return the index of the minimum. Series.idxmax Return the index of the maximum. DataFrame.sum Return the sum over the requested axis. DataFrame.min Return the minimum over the requested axis. DataFrame.max Return the maximum over the requested axis. DataFrame.idxmin Return the index of the minimum over the requested axis. DataFrame.idxmax Return the index of the maximum over the requested axis. Examples >>> idx = pd.MultiIndex.from_arrays([ ... ['warm', 'warm', 'cold', 'cold'], ... ['dog', 'falcon', 'fish', 'spider']], ... names=['blooded', 'animal']) >>> s = pd.Series([4, 2, 0, 8], name='legs', index=idx) >>> s blooded animal warm dog 4 falcon 2 cold fish 0 spider 8 Name: legs, dtype: int64 >>> s.max() 8
pandas.reference.api.pandas.series.max