pandas.MultiIndex.get_loc_level   MultiIndex.get_loc_level(key, level=0, drop_level=True)[source]

Get location and sliced index for requested label(s)/level(s).  Parameters

key:label or sequence of labels

level:int/level name or list thereof, optional

drop_level:bool, default True

If False, the resulting index will not drop any level.    Returns

loc:A 2-tuple where the elements are:

Element 0: int, slice object or boolean array Element 1: The resulting sliced multiindex/index. If the key contains all levels, this will be None.      See also  MultiIndex.get_loc

Get location for a label or a tuple of labels.  MultiIndex.get_locs

Get location for a label/slice/list/mask or a sequence of such.    Examples
>>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')],
...                                names=['A', 'B'])

>>> mi.get_loc_level('b')
(slice(1, 3, None), Index(['e', 'f'], dtype='object', name='B'))

>>> mi.get_loc_level('e', level='B')
(array([False,  True, False]), Index(['b'], dtype='object', name='A'))

>>> mi.get_loc_level(['b', 'e'])
(1, None)


pandas.MultiIndex.get_locs   MultiIndex.get_locs(seq)[source]

Get location for a sequence of labels.  Parameters

seq:label, slice, list, mask or a sequence of such

You should use one of the above for each level. If a level should not be used, set it to slice(None).    Returns
 numpy.ndarray

NumPy array of integers suitable for passing to iloc.      See also  MultiIndex.get_loc

Get location for a label or a tuple of labels.  MultiIndex.slice_locs

Get slice location given start label(s) and end label(s).    Examples
>>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')])

>>> mi.get_locs('b')
array([1, 2], dtype=int64)

>>> mi.get_locs([slice(None), ['e', 'f']])
array([1, 2], dtype=int64)

>>> mi.get_locs([[True, False, True], slice('e', 'f')])
array([2], dtype=int64)


pandas.MultiIndex.levels   MultiIndex.levels


pandas.MultiIndex.levshape   propertyMultiIndex.levshape

A tuple with the length of each level. Examples
>>> mi = pd.MultiIndex.from_arrays([['a'], ['b'], ['c']])
>>> mi
MultiIndex([('a', 'b', 'c')],
           )
>>> mi.levshape
(1, 1, 1)


pandas.MultiIndex.names   propertyMultiIndex.names

Names of levels in MultiIndex. Examples
>>> mi = pd.MultiIndex.from_arrays(
... [[1, 2], [3, 4], [5, 6]], names=['x', 'y', 'z'])
>>> mi
MultiIndex([(1, 3, 5),
            (2, 4, 6)],
           names=['x', 'y', 'z'])
>>> mi.names
FrozenList(['x', 'y', 'z'])


pandas.MultiIndex.nlevels   propertyMultiIndex.nlevels

Integer number of levels in this MultiIndex. Examples
>>> mi = pd.MultiIndex.from_arrays([['a'], ['b'], ['c']])
>>> mi
MultiIndex([('a', 'b', 'c')],
           )
>>> mi.nlevels
3


pandas.MultiIndex.remove_unused_levels   MultiIndex.remove_unused_levels()[source]

Create new MultiIndex from current that removes unused levels. Unused level(s) means levels that are not expressed in the labels. The resulting MultiIndex will have the same outward appearance, meaning the same .values and ordering. It will also be .equals() to the original.  Returns
 MultiIndex
   Examples
>>> mi = pd.MultiIndex.from_product([range(2), list('ab')])
>>> mi
MultiIndex([(0, 'a'),
            (0, 'b'),
            (1, 'a'),
            (1, 'b')],
           )

>>> mi[2:]
MultiIndex([(1, 'a'),
            (1, 'b')],
           )
  The 0 from the first level is not represented and can be removed
>>> mi2 = mi[2:].remove_unused_levels()
>>> mi2.levels
FrozenList([[1], ['a', 'b']])


pandas.MultiIndex.reorder_levels   MultiIndex.reorder_levels(order)[source]

Rearrange levels using input order. May not drop or duplicate levels.  Parameters

order:list of int or list of str

List representing new level order. Reference level by number (position) or by key (label).    Returns
 MultiIndex
   Examples
>>> mi = pd.MultiIndex.from_arrays([[1, 2], [3, 4]], names=['x', 'y'])
>>> mi
MultiIndex([(1, 3),
            (2, 4)],
           names=['x', 'y'])

>>> mi.reorder_levels(order=[1, 0])
MultiIndex([(3, 1),
            (4, 2)],
           names=['y', 'x'])

>>> mi.reorder_levels(order=['y', 'x'])
MultiIndex([(3, 1),
            (4, 2)],
           names=['y', 'x'])


pandas.MultiIndex.set_codes   MultiIndex.set_codes(codes, level=None, inplace=None, verify_integrity=True)[source]

Set new codes on MultiIndex. Defaults to returning new index.  Parameters

codes:sequence or list of sequence

New codes to apply.
level:int, level name, or sequence of int/level names (default None)

Level(s) to set (None for all levels).
inplace:bool

If True, mutates in place.  Deprecated since version 1.2.0.
verify_integrity:bool, default True

If True, checks that levels and codes are compatible.    Returns
 new index (of same type and class…etc) or None

The same type as the caller or None if inplace=True.     Examples
>>> idx = pd.MultiIndex.from_tuples(
...     [(1, "one"), (1, "two"), (2, "one"), (2, "two")], names=["foo", "bar"]
... )
>>> idx
MultiIndex([(1, 'one'),
    (1, 'two'),
    (2, 'one'),
    (2, 'two')],
   names=['foo', 'bar'])

>>> idx.set_codes([[1, 0, 1, 0], [0, 0, 1, 1]])
MultiIndex([(2, 'one'),
            (1, 'one'),
            (2, 'two'),
            (1, 'two')],
           names=['foo', 'bar'])
>>> idx.set_codes([1, 0, 1, 0], level=0)
MultiIndex([(2, 'one'),
            (1, 'two'),
            (2, 'one'),
            (1, 'two')],
           names=['foo', 'bar'])
>>> idx.set_codes([0, 0, 1, 1], level='bar')
MultiIndex([(1, 'one'),
            (1, 'one'),
            (2, 'two'),
            (2, 'two')],
           names=['foo', 'bar'])
>>> idx.set_codes([[1, 0, 1, 0], [0, 0, 1, 1]], level=[0, 1])
MultiIndex([(2, 'one'),
            (1, 'one'),
            (2, 'two'),
            (1, 'two')],
           names=['foo', 'bar'])


pandas.MultiIndex.set_levels   MultiIndex.set_levels(levels, level=None, inplace=None, verify_integrity=True)[source]

Set new levels on MultiIndex. Defaults to returning new index.  Parameters

levels:sequence or list of sequence

New level(s) to apply.
level:int, level name, or sequence of int/level names (default None)

Level(s) to set (None for all levels).
inplace:bool

If True, mutates in place.  Deprecated since version 1.2.0.
verify_integrity:bool, default True

If True, checks that levels and codes are compatible.    Returns
 new index (of same type and class…etc) or None

The same type as the caller or None if inplace=True.     Examples
>>> idx = pd.MultiIndex.from_tuples(
...     [
...         (1, "one"),
...         (1, "two"),
...         (2, "one"),
...         (2, "two"),
...         (3, "one"),
...         (3, "two")
...     ],
...     names=["foo", "bar"]
... )
>>> idx
MultiIndex([(1, 'one'),
    (1, 'two'),
    (2, 'one'),
    (2, 'two'),
    (3, 'one'),
    (3, 'two')],
   names=['foo', 'bar'])

>>> idx.set_levels([['a', 'b', 'c'], [1, 2]])
MultiIndex([('a', 1),
            ('a', 2),
            ('b', 1),
            ('b', 2),
            ('c', 1),
            ('c', 2)],
           names=['foo', 'bar'])
>>> idx.set_levels(['a', 'b', 'c'], level=0)
MultiIndex([('a', 'one'),
            ('a', 'two'),
            ('b', 'one'),
            ('b', 'two'),
            ('c', 'one'),
            ('c', 'two')],
           names=['foo', 'bar'])
>>> idx.set_levels(['a', 'b'], level='bar')
MultiIndex([(1, 'a'),
            (1, 'b'),
            (2, 'a'),
            (2, 'b'),
            (3, 'a'),
            (3, 'b')],
           names=['foo', 'bar'])
  If any of the levels passed to set_levels() exceeds the existing length, all of the values from that argument will be stored in the MultiIndex levels, though the values will be truncated in the MultiIndex output.
>>> idx.set_levels([['a', 'b', 'c'], [1, 2, 3, 4]], level=[0, 1])
MultiIndex([('a', 1),
    ('a', 2),
    ('b', 1),
    ('b', 2),
    ('c', 1),
    ('c', 2)],
   names=['foo', 'bar'])
>>> idx.set_levels([['a', 'b', 'c'], [1, 2, 3, 4]], level=[0, 1]).levels
FrozenList([['a', 'b', 'c'], [1, 2, 3, 4]])


pandas.MultiIndex.sortlevel   MultiIndex.sortlevel(level=0, ascending=True, sort_remaining=True)[source]

Sort MultiIndex at the requested level. The result will respect the original ordering of the associated factor at that level.  Parameters

level:list-like, int or str, default 0

If a string is given, must be a name of the level. If list-like must be names or ints of levels.
ascending:bool, default True

False to sort in descending order. Can also be a list to specify a directed ordering.
sort_remaining:sort by the remaining levels after level

  Returns

sorted_index:pd.MultiIndex

Resulting index.
indexer:np.ndarray[np.intp]

Indices of output values in original index.     Examples
>>> mi = pd.MultiIndex.from_arrays([[0, 0], [2, 1]])
>>> mi
MultiIndex([(0, 2),
            (0, 1)],
           )

>>> mi.sortlevel()
(MultiIndex([(0, 1),
            (0, 2)],
           ), array([1, 0]))

>>> mi.sortlevel(sort_remaining=False)
(MultiIndex([(0, 2),
            (0, 1)],
           ), array([0, 1]))

>>> mi.sortlevel(1)
(MultiIndex([(0, 1),
            (0, 2)],
           ), array([1, 0]))

>>> mi.sortlevel(1, ascending=False)
(MultiIndex([(0, 2),
            (0, 1)],
           ), array([0, 1]))


pandas.MultiIndex.swaplevel   MultiIndex.swaplevel(i=- 2, j=- 1)[source]

Swap level i with level j. Calling this method does not change the ordering of the values.  Parameters

i:int, str, default -2

First level of index to be swapped. Can pass level name as string. Type of parameters can be mixed.
j:int, str, default -1

Second level of index to be swapped. Can pass level name as string. Type of parameters can be mixed.    Returns
 MultiIndex

A new MultiIndex.      See also  Series.swaplevel

Swap levels i and j in a MultiIndex.  Dataframe.swaplevel

Swap levels i and j in a MultiIndex on a particular axis.    Examples
>>> mi = pd.MultiIndex(levels=[['a', 'b'], ['bb', 'aa']],
...                    codes=[[0, 0, 1, 1], [0, 1, 0, 1]])
>>> mi
MultiIndex([('a', 'bb'),
            ('a', 'aa'),
            ('b', 'bb'),
            ('b', 'aa')],
           )
>>> mi.swaplevel(0, 1)
MultiIndex([('bb', 'a'),
            ('aa', 'a'),
            ('bb', 'b'),
            ('aa', 'b')],
           )


pandas.MultiIndex.to_flat_index   MultiIndex.to_flat_index()[source]

Convert a MultiIndex to an Index of Tuples containing the level values.  Returns
 pd.Index

Index with the MultiIndex data represented in Tuples.      See also  MultiIndex.from_tuples

Convert flat index back to MultiIndex.    Notes This method will simply return the caller if called by anything other than a MultiIndex. Examples
>>> index = pd.MultiIndex.from_product(
...     [['foo', 'bar'], ['baz', 'qux']],
...     names=['a', 'b'])
>>> index.to_flat_index()
Index([('foo', 'baz'), ('foo', 'qux'),
       ('bar', 'baz'), ('bar', 'qux')],
      dtype='object')


pandas.MultiIndex.to_frame   MultiIndex.to_frame(index=True, name=NoDefault.no_default)[source]

Create a DataFrame with the levels of the MultiIndex as columns. Column ordering is determined by the DataFrame constructor with data as a dict.  Parameters

index:bool, default True

Set the index of the returned DataFrame as the original MultiIndex.
name:list / sequence of str, optional

The passed names should substitute index level names.    Returns

DataFrame:a DataFrame containing the original MultiIndex data.

    See also  DataFrame

Two-dimensional, size-mutable, potentially heterogeneous tabular data.    Examples
>>> mi = pd.MultiIndex.from_arrays([['a', 'b'], ['c', 'd']])
>>> mi
MultiIndex([('a', 'c'),
            ('b', 'd')],
           )

>>> df = mi.to_frame()
>>> df
     0  1
a c  a  c
b d  b  d

>>> df = mi.to_frame(index=False)
>>> df
   0  1
0  a  c
1  b  d

>>> df = mi.to_frame(name=['x', 'y'])
>>> df
     x  y
a c  a  c
b d  b  d


pandas.notna   pandas.notna(obj)[source]

Detect non-missing values for an array-like object. This function takes a scalar or array-like object and indicates whether values are valid (not missing, which is NaN in numeric arrays, None or NaN in object arrays, NaT in datetimelike).  Parameters

obj:array-like or object value

Object to check for not null or non-missing values.    Returns
 bool or array-like of bool

For scalar input, returns a scalar boolean. For array input, returns an array of boolean indicating whether each corresponding element is valid.      See also  isna

Boolean inverse of pandas.notna.  Series.notna

Detect valid values in a Series.  DataFrame.notna

Detect valid values in a DataFrame.  Index.notna

Detect valid values in an Index.    Examples Scalar arguments (including strings) result in a scalar boolean.
>>> pd.notna('dog')
True

>>> pd.notna(pd.NA)
False

>>> pd.notna(np.nan)
False
  ndarrays result in an ndarray of booleans.
>>> array = np.array([[1, np.nan, 3], [4, 5, np.nan]])
>>> array
array([[ 1., nan,  3.],
       [ 4.,  5., nan]])
>>> pd.notna(array)
array([[ True, False,  True],
       [ True,  True, False]])
  For indexes, an ndarray of booleans is returned.
>>> index = pd.DatetimeIndex(["2017-07-05", "2017-07-06", None,
...                          "2017-07-08"])
>>> index
DatetimeIndex(['2017-07-05', '2017-07-06', 'NaT', '2017-07-08'],
              dtype='datetime64[ns]', freq=None)
>>> pd.notna(index)
array([ True,  True, False,  True])
  For Series and DataFrame, the same type is returned, containing booleans.
>>> df = pd.DataFrame([['ant', 'bee', 'cat'], ['dog', None, 'fly']])
>>> df
     0     1    2
0  ant   bee  cat
1  dog  None  fly
>>> pd.notna(df)
      0      1     2
0  True   True  True
1  True  False  True

>>> pd.notna(df[1])
0     True
1    False
Name: 1, dtype: bool


pandas.notnull   pandas.notnull(obj)[source]

Detect non-missing values for an array-like object. This function takes a scalar or array-like object and indicates whether values are valid (not missing, which is NaN in numeric arrays, None or NaN in object arrays, NaT in datetimelike).  Parameters

obj:array-like or object value

Object to check for not null or non-missing values.    Returns
 bool or array-like of bool

For scalar input, returns a scalar boolean. For array input, returns an array of boolean indicating whether each corresponding element is valid.      See also  isna

Boolean inverse of pandas.notna.  Series.notna

Detect valid values in a Series.  DataFrame.notna

Detect valid values in a DataFrame.  Index.notna

Detect valid values in an Index.    Examples Scalar arguments (including strings) result in a scalar boolean.
>>> pd.notna('dog')
True

>>> pd.notna(pd.NA)
False

>>> pd.notna(np.nan)
False
  ndarrays result in an ndarray of booleans.
>>> array = np.array([[1, np.nan, 3], [4, 5, np.nan]])
>>> array
array([[ 1., nan,  3.],
       [ 4.,  5., nan]])
>>> pd.notna(array)
array([[ True, False,  True],
       [ True,  True, False]])
  For indexes, an ndarray of booleans is returned.
>>> index = pd.DatetimeIndex(["2017-07-05", "2017-07-06", None,
...                          "2017-07-08"])
>>> index
DatetimeIndex(['2017-07-05', '2017-07-06', 'NaT', '2017-07-08'],
              dtype='datetime64[ns]', freq=None)
>>> pd.notna(index)
array([ True,  True, False,  True])
  For Series and DataFrame, the same type is returned, containing booleans.
>>> df = pd.DataFrame([['ant', 'bee', 'cat'], ['dog', None, 'fly']])
>>> df
     0     1    2
0  ant   bee  cat
1  dog  None  fly
>>> pd.notna(df)
      0      1     2
0  True   True  True
1  True  False  True

>>> pd.notna(df[1])
0     True
1    False
Name: 1, dtype: bool


pandas.option_context   classpandas.option_context(*args)[source]

Context manager to temporarily set options in the with statement context. You need to invoke as option_context(pat, val, [(pat, val), ...]). Examples
>>> with option_context('display.max_rows', 10, 'display.max_columns', 5):
...     pass
  Methods
__call__(func) Call self as a function.


pandas.option_context.__call__   option_context.__call__(func)[source]

Call self as a function.


pandas.Period   classpandas.Period(value=None, freq=None, ordinal=None, year=None, month=None, quarter=None, day=None, hour=None, minute=None, second=None)

Represents a period of time.  Parameters

value:Period or str, default None

The time period represented (e.g., ‘4Q2005’).
freq:str, default None

One of pandas period strings or corresponding objects.
ordinal:int, default None

The period offset from the proleptic Gregorian epoch.
year:int, default None

Year value of the period.
month:int, default 1

Month value of the period.
quarter:int, default None

Quarter value of the period.
day:int, default 1

Day value of the period.
hour:int, default 0

Hour value of the period.
minute:int, default 0

Minute value of the period.
second:int, default 0

Second value of the period.     Attributes
day Get day of the month that a Period falls on.
day_of_week Day of the week the period lies in, with Monday=0 and Sunday=6.
day_of_year Return the day of the year.
dayofweek Day of the week the period lies in, with Monday=0 and Sunday=6.
dayofyear Return the day of the year.
days_in_month Get the total number of days in the month that this period falls on.
daysinmonth Get the total number of days of the month that the Period falls in.
end_time Get the Timestamp for the end of the period.
freqstr Return a string representation of the frequency.
hour Get the hour of the day component of the Period.
is_leap_year Return True if the period's year is in a leap year.
minute Get minute of the hour component of the Period.
month Return the month this Period falls on.
quarter Return the quarter this Period falls on.
qyear Fiscal year the Period lies in according to its starting-quarter.
second Get the second component of the Period.
start_time Get the Timestamp for the start of the period.
week Get the week of the year on the given Period.
weekday Day of the week the period lies in, with Monday=0 and Sunday=6.
weekofyear Get the week of the year on the given Period.
year Return the year this Period falls on.
freq
ordinal     Methods
asfreq Convert Period to desired frequency, at the start or end of the interval.
now Return the period of now's date.
strftime Returns the string representation of the Period, depending on the selected fmt.
to_timestamp Return the Timestamp representation of the Period.


pandas.Period.asfreq   Period.asfreq()

Convert Period to desired frequency, at the start or end of the interval.  Parameters

freq:str

The desired frequency.
how:{‘E’, ‘S’, ‘end’, ‘start’}, default ‘end’

Start or end of the timespan.    Returns

resampled:Period


pandas.Period.day   Period.day

Get day of the month that a Period falls on.  Returns
 int
    See also  Period.dayofweek

Get the day of the week.  Period.dayofyear

Get the day of the year.    Examples
>>> p = pd.Period("2018-03-11", freq='H')
>>> p.day
11


pandas.Period.day_of_week   Period.day_of_week

Day of the week the period lies in, with Monday=0 and Sunday=6. If the period frequency is lower than daily (e.g. hourly), and the period spans over multiple days, the day at the start of the period is used. If the frequency is higher than daily (e.g. monthly), the last day of the period is used.  Returns
 int

Day of the week.      See also  Period.day_of_week

Day of the week the period lies in.  Period.weekday

Alias of Period.day_of_week.  Period.day

Day of the month.  Period.dayofyear

Day of the year.    Examples
>>> per = pd.Period('2017-12-31 22:00', 'H')
>>> per.day_of_week
6
  For periods that span over multiple days, the day at the beginning of the period is returned.
>>> per = pd.Period('2017-12-31 22:00', '4H')
>>> per.day_of_week
6
>>> per.start_time.day_of_week
6
  For periods with a frequency higher than days, the last day of the period is returned.
>>> per = pd.Period('2018-01', 'M')
>>> per.day_of_week
2
>>> per.end_time.day_of_week
2


pandas.Period.day_of_year   Period.day_of_year

Return the day of the year. This attribute returns the day of the year on which the particular date occurs. The return value ranges between 1 to 365 for regular years and 1 to 366 for leap years.  Returns
 int

The day of year.      See also  Period.day

Return the day of the month.  Period.day_of_week

Return the day of week.  PeriodIndex.day_of_year

Return the day of year of all indexes.    Examples
>>> period = pd.Period("2015-10-23", freq='H')
>>> period.day_of_year
296
>>> period = pd.Period("2012-12-31", freq='D')
>>> period.day_of_year
366
>>> period = pd.Period("2013-01-01", freq='D')
>>> period.day_of_year
1


pandas.Period.dayofweek   Period.dayofweek

Day of the week the period lies in, with Monday=0 and Sunday=6. If the period frequency is lower than daily (e.g. hourly), and the period spans over multiple days, the day at the start of the period is used. If the frequency is higher than daily (e.g. monthly), the last day of the period is used.  Returns
 int

Day of the week.      See also  Period.day_of_week

Day of the week the period lies in.  Period.weekday

Alias of Period.day_of_week.  Period.day

Day of the month.  Period.dayofyear

Day of the year.    Examples
>>> per = pd.Period('2017-12-31 22:00', 'H')
>>> per.day_of_week
6
  For periods that span over multiple days, the day at the beginning of the period is returned.
>>> per = pd.Period('2017-12-31 22:00', '4H')
>>> per.day_of_week
6
>>> per.start_time.day_of_week
6
  For periods with a frequency higher than days, the last day of the period is returned.
>>> per = pd.Period('2018-01', 'M')
>>> per.day_of_week
2
>>> per.end_time.day_of_week
2


pandas.Period.dayofyear   Period.dayofyear

Return the day of the year. This attribute returns the day of the year on which the particular date occurs. The return value ranges between 1 to 365 for regular years and 1 to 366 for leap years.  Returns
 int

The day of year.      See also  Period.day

Return the day of the month.  Period.day_of_week

Return the day of week.  PeriodIndex.day_of_year

Return the day of year of all indexes.    Examples
>>> period = pd.Period("2015-10-23", freq='H')
>>> period.day_of_year
296
>>> period = pd.Period("2012-12-31", freq='D')
>>> period.day_of_year
366
>>> period = pd.Period("2013-01-01", freq='D')
>>> period.day_of_year
1


pandas.Period.days_in_month   Period.days_in_month

Get the total number of days in the month that this period falls on.  Returns
 int
    See also  Period.daysinmonth

Gets the number of days in the month.  DatetimeIndex.daysinmonth

Gets the number of days in the month.  calendar.monthrange

Returns a tuple containing weekday (0-6 ~ Mon-Sun) and number of days (28-31).    Examples
>>> p = pd.Period('2018-2-17')
>>> p.days_in_month
28

>>> pd.Period('2018-03-01').days_in_month
31
  Handles the leap year case as well:
>>> p = pd.Period('2016-2-17')
>>> p.days_in_month
29


pandas.Period.daysinmonth   Period.daysinmonth

Get the total number of days of the month that the Period falls in.  Returns
 int
    See also  Period.days_in_month

Return the days of the month.  Period.dayofyear

Return the day of the year.    Examples
>>> p = pd.Period("2018-03-11", freq='H')
>>> p.daysinmonth
31


pandas.Period.end_time   Period.end_time

Get the Timestamp for the end of the period.  Returns
 Timestamp
    See also  Period.start_time

Return the start Timestamp.  Period.dayofyear

Return the day of year.  Period.daysinmonth

Return the days in that month.  Period.dayofweek

Return the day of the week.


pandas.Period.freqstr   Period.freqstr

Return a string representation of the frequency.


pandas.Period.hour   Period.hour

Get the hour of the day component of the Period.  Returns
 int

The hour as an integer, between 0 and 23.      See also  Period.second

Get the second component of the Period.  Period.minute

Get the minute component of the Period.    Examples
>>> p = pd.Period("2018-03-11 13:03:12.050000")
>>> p.hour
13
  Period longer than a day
>>> p = pd.Period("2018-03-11", freq="M")
>>> p.hour
0


pandas.Period.is_leap_year   Period.is_leap_year

Return True if the period’s year is in a leap year.


pandas.Period.minute   Period.minute

Get minute of the hour component of the Period.  Returns
 int

The minute as an integer, between 0 and 59.      See also  Period.hour

Get the hour component of the Period.  Period.second

Get the second component of the Period.    Examples
>>> p = pd.Period("2018-03-11 13:03:12.050000")
>>> p.minute
3


pandas.Period.month   Period.month

Return the month this Period falls on.


pandas.Period.now   Period.now()

Return the period of now’s date.


pandas.Period.quarter   Period.quarter

Return the quarter this Period falls on.


pandas.Period.qyear   Period.qyear

Fiscal year the Period lies in according to its starting-quarter. The year and the qyear of the period will be the same if the fiscal and calendar years are the same. When they are not, the fiscal year can be different from the calendar year of the period.  Returns
 int

The fiscal year of the period.      See also  Period.year

Return the calendar year of the period.    Examples If the natural and fiscal year are the same, qyear and year will be the same.
>>> per = pd.Period('2018Q1', freq='Q')
>>> per.qyear
2018
>>> per.year
2018
  If the fiscal year starts in April (Q-MAR), the first quarter of 2018 will start in April 2017. year will then be 2018, but qyear will be the fiscal year, 2018.
>>> per = pd.Period('2018Q1', freq='Q-MAR')
>>> per.start_time
Timestamp('2017-04-01 00:00:00')
>>> per.qyear
2018
>>> per.year
2017


pandas.Period.second   Period.second

Get the second component of the Period.  Returns
 int

The second of the Period (ranges from 0 to 59).      See also  Period.hour

Get the hour component of the Period.  Period.minute

Get the minute component of the Period.    Examples
>>> p = pd.Period("2018-03-11 13:03:12.050000")
>>> p.second
12


pandas.Period.start_time   Period.start_time

Get the Timestamp for the start of the period.  Returns
 Timestamp
    See also  Period.end_time

Return the end Timestamp.  Period.dayofyear

Return the day of year.  Period.daysinmonth

Return the days in that month.  Period.dayofweek

Return the day of the week.    Examples
>>> period = pd.Period('2012-1-1', freq='D')
>>> period
Period('2012-01-01', 'D')

>>> period.start_time
Timestamp('2012-01-01 00:00:00')

>>> period.end_time
Timestamp('2012-01-01 23:59:59.999999999')


pandas.Period.strftime   Period.strftime()

Returns the string representation of the Period, depending on the selected fmt. fmt must be a string containing one or several directives. The method recognizes the same directives as the time.strftime() function of the standard Python distribution, as well as the specific additional directives %f, %F, %q. (formatting & docs originally from scikits.timeries).
Directive Meaning Notes
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%f ‘Fiscal’ year without a century as a decimal number [00,99] (1)
%F ‘Fiscal’ year with a century as a decimal number (2)
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale’s equivalent of either AM or PM. (3)
%q Quarter as a decimal number [01,04]
%S Second as a decimal number [00,61]. (4)
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (5)
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (5)
%x Locale’s appropriate date representation.
%X Locale’s appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%Z Time zone name (no characters if no time zone exists).
%% A literal '%' character.     Notes  The %f directive is the same as %y if the frequency is not quarterly. Otherwise, it corresponds to the ‘fiscal’ year, as defined by the qyear attribute. The %F directive is the same as %Y if the frequency is not quarterly. Otherwise, it corresponds to the ‘fiscal’ year, as defined by the qyear attribute. The %p directive only affects the output hour field if the %I directive is used to parse the hour. The range really is 0 to 61; this accounts for leap seconds and the (very rare) double leap seconds. The %U and %W directives are only used in calculations when the day of the week and the year are specified.  Examples
>>> a = Period(freq='Q-JUL', year=2006, quarter=1)
>>> a.strftime('%F-Q%q')
'2006-Q1'
>>> # Output the last month in the quarter of this date
>>> a.strftime('%b-%Y')
'Oct-2005'
>>>
>>> a = Period(freq='D', year=2001, month=1, day=1)
>>> a.strftime('%d-%b-%Y')
'01-Jan-2001'
>>> a.strftime('%b. %d, %Y was a %A')
'Jan. 01, 2001 was a Monday'


pandas.Period.to_timestamp   Period.to_timestamp()

Return the Timestamp representation of the Period. Uses the target frequency specified at the part of the period specified by how, which is either Start or Finish.  Parameters

freq:str or DateOffset

Target frequency. Default is ‘D’ if self.freq is week or longer and ‘S’ otherwise.
how:str, default ‘S’ (start)

One of ‘S’, ‘E’. Can be aliased as case insensitive ‘Start’, ‘Finish’, ‘Begin’, ‘End’.    Returns
 Timestamp


pandas.Period.week   Period.week

Get the week of the year on the given Period.  Returns
 int
    See also  Period.dayofweek

Get the day component of the Period.  Period.weekday

Get the day component of the Period.    Examples
>>> p = pd.Period("2018-03-11", "H")
>>> p.week
10

>>> p = pd.Period("2018-02-01", "D")
>>> p.week
5

>>> p = pd.Period("2018-01-06", "D")
>>> p.week
1


pandas.Period.weekday   Period.weekday

Day of the week the period lies in, with Monday=0 and Sunday=6. If the period frequency is lower than daily (e.g. hourly), and the period spans over multiple days, the day at the start of the period is used. If the frequency is higher than daily (e.g. monthly), the last day of the period is used.  Returns
 int

Day of the week.      See also  Period.dayofweek

Day of the week the period lies in.  Period.weekday

Alias of Period.dayofweek.  Period.day

Day of the month.  Period.dayofyear

Day of the year.    Examples
>>> per = pd.Period('2017-12-31 22:00', 'H')
>>> per.dayofweek
6
  For periods that span over multiple days, the day at the beginning of the period is returned.
>>> per = pd.Period('2017-12-31 22:00', '4H')
>>> per.dayofweek
6
>>> per.start_time.dayofweek
6
  For periods with a frequency higher than days, the last day of the period is returned.
>>> per = pd.Period('2018-01', 'M')
>>> per.dayofweek
2
>>> per.end_time.dayofweek
2


pandas.Period.weekofyear   Period.weekofyear

Get the week of the year on the given Period.  Returns
 int
    See also  Period.dayofweek

Get the day component of the Period.  Period.weekday

Get the day component of the Period.    Examples
>>> p = pd.Period("2018-03-11", "H")
>>> p.weekofyear
10

>>> p = pd.Period("2018-02-01", "D")
>>> p.weekofyear
5

>>> p = pd.Period("2018-01-06", "D")
>>> p.weekofyear
1


pandas.Period.year   Period.year

Return the year this Period falls on.


pandas.period_range   pandas.period_range(start=None, end=None, periods=None, freq=None, name=None)[source]

Return a fixed frequency PeriodIndex. The day (calendar) is the default frequency.  Parameters

start:str or period-like, default None

Left bound for generating periods.
end:str or period-like, default None

Right bound for generating periods.
periods:int, default None

Number of periods to generate.
freq:str or DateOffset, optional

Frequency alias. By default the freq is taken from start or end if those are Period objects. Otherwise, the default is "D" for daily frequency.
name:str, default None

Name of the resulting PeriodIndex.    Returns
 PeriodIndex
   Notes Of the three parameters: start, end, and periods, exactly two must be specified. To learn more about the frequency strings, please see this link. Examples
>>> pd.period_range(start='2017-01-01', end='2018-01-01', freq='M')
PeriodIndex(['2017-01', '2017-02', '2017-03', '2017-04', '2017-05', '2017-06',
         '2017-07', '2017-08', '2017-09', '2017-10', '2017-11', '2017-12',
         '2018-01'],
        dtype='period[M]')
  If start or end are Period objects, they will be used as anchor endpoints for a PeriodIndex with frequency matching that of the period_range constructor.
>>> pd.period_range(start=pd.Period('2017Q1', freq='Q'),
...                 end=pd.Period('2017Q2', freq='Q'), freq='M')
PeriodIndex(['2017-03', '2017-04', '2017-05', '2017-06'],
            dtype='period[M]')


pandas.PeriodDtype   classpandas.PeriodDtype(freq=None)[source]

An ExtensionDtype for Period data. This is not an actual numpy dtype, but a duck type.  Parameters

freq:str or DateOffset

The frequency of this PeriodDtype.     Examples
>>> pd.PeriodDtype(freq='D')
period[D]

>>> pd.PeriodDtype(freq=pd.offsets.MonthEnd())
period[M]
  Attributes
freq The frequency object of this PeriodDtype.    Methods
None


pandas.PeriodDtype.freq   propertyPeriodDtype.freq

The frequency object of this PeriodDtype.


pandas.PeriodIndex   classpandas.PeriodIndex(data=None, ordinal=None, freq=None, dtype=None, copy=False, name=None, **fields)[source]

Immutable ndarray holding ordinal values indicating regular periods in time. Index keys are boxed to Period objects which carries the metadata (eg, frequency information).  Parameters

data:array-like (1d int np.ndarray or PeriodArray), optional

Optional period-like data to construct index with.
copy:bool

Make a copy of input ndarray.
freq:str or period object, optional

One of pandas period strings or corresponding objects.
year:int, array, or Series, default None

month:int, array, or Series, default None

quarter:int, array, or Series, default None

day:int, array, or Series, default None

hour:int, array, or Series, default None

minute:int, array, or Series, default None

second:int, array, or Series, default None

dtype:str or PeriodDtype, default None

    See also  Index

The base pandas Index type.  Period

Represents a period of time.  DatetimeIndex

Index with datetime64 data.  TimedeltaIndex

Index of timedelta64 data.  period_range

Create a fixed-frequency PeriodIndex.    Examples
>>> idx = pd.PeriodIndex(year=[2000, 2002], quarter=[1, 3])
>>> idx
PeriodIndex(['2000Q1', '2002Q3'], dtype='period[Q-DEC]')
  Attributes
day The days of the period.
dayofweek The day of the week with Monday=0, Sunday=6.
day_of_week The day of the week with Monday=0, Sunday=6.
dayofyear The ordinal day of the year.
day_of_year The ordinal day of the year.
days_in_month The number of days in the month.
daysinmonth The number of days in the month.
freq Return the frequency object if it is set, otherwise None.
freqstr Return the frequency object as a string if its set, otherwise None.
hour The hour of the period.
is_leap_year Logical indicating if the date belongs to a leap year.
minute The minute of the period.
month The month as January=1, December=12.
quarter The quarter of the date.
second The second of the period.
week The week ordinal of the year.
weekday The day of the week with Monday=0, Sunday=6.
weekofyear The week ordinal of the year.
year The year of the period.
end_time
qyear
start_time     Methods
asfreq([freq, how]) Convert the PeriodArray to the specified frequency freq.
strftime(*args, **kwargs) Convert to Index using specified date_format.
to_timestamp([freq, how]) Cast to DatetimeArray/Index.


pandas.PeriodIndex.asfreq   PeriodIndex.asfreq(freq=None, how='E')[source]

Convert the PeriodArray to the specified frequency freq. Equivalent to applying pandas.Period.asfreq() with the given arguments to each Period in this PeriodArray.  Parameters

freq:str

A frequency.
how:str {‘E’, ‘S’}, default ‘E’

Whether the elements should be aligned to the end or start within pa period.  ‘E’, ‘END’, or ‘FINISH’ for end, ‘S’, ‘START’, or ‘BEGIN’ for start.  January 31st (‘END’) vs. January 1st (‘START’) for example.    Returns
 PeriodArray

The transformed PeriodArray with the new frequency.      See also  pandas.arrays.PeriodArray.asfreq

Convert each Period in a PeriodArray to the given frequency.  Period.asfreq

Convert a Period object to the given frequency.    Examples
>>> pidx = pd.period_range('2010-01-01', '2015-01-01', freq='A')
>>> pidx
PeriodIndex(['2010', '2011', '2012', '2013', '2014', '2015'],
dtype='period[A-DEC]')

>>> pidx.asfreq('M')
PeriodIndex(['2010-12', '2011-12', '2012-12', '2013-12', '2014-12',
'2015-12'], dtype='period[M]')

>>> pidx.asfreq('M', how='S')
PeriodIndex(['2010-01', '2011-01', '2012-01', '2013-01', '2014-01',
'2015-01'], dtype='period[M]')


pandas.PeriodIndex.day   propertyPeriodIndex.day

The days of the period.


pandas.PeriodIndex.day_of_week   propertyPeriodIndex.day_of_week

The day of the week with Monday=0, Sunday=6.


pandas.PeriodIndex.day_of_year   propertyPeriodIndex.day_of_year

The ordinal day of the year.


pandas.PeriodIndex.dayofweek   propertyPeriodIndex.dayofweek

The day of the week with Monday=0, Sunday=6.


pandas.PeriodIndex.dayofyear   propertyPeriodIndex.dayofyear

The ordinal day of the year.


pandas.PeriodIndex.days_in_month   propertyPeriodIndex.days_in_month

The number of days in the month.


pandas.PeriodIndex.daysinmonth   propertyPeriodIndex.daysinmonth

The number of days in the month.


pandas.PeriodIndex.end_time   propertyPeriodIndex.end_time


pandas.PeriodIndex.freq   propertyPeriodIndex.freq

Return the frequency object if it is set, otherwise None.


pandas.PeriodIndex.freqstr   propertyPeriodIndex.freqstr

Return the frequency object as a string if its set, otherwise None.


pandas.PeriodIndex.hour   propertyPeriodIndex.hour

The hour of the period.


pandas.PeriodIndex.is_leap_year   propertyPeriodIndex.is_leap_year

Logical indicating if the date belongs to a leap year.


pandas.PeriodIndex.minute   propertyPeriodIndex.minute

The minute of the period.


pandas.PeriodIndex.month   propertyPeriodIndex.month

The month as January=1, December=12.


pandas.PeriodIndex.quarter   propertyPeriodIndex.quarter

The quarter of the date.


pandas.PeriodIndex.qyear   propertyPeriodIndex.qyear


pandas.PeriodIndex.second   propertyPeriodIndex.second

The second of the period.


pandas.PeriodIndex.start_time   propertyPeriodIndex.start_time


pandas.PeriodIndex.strftime   PeriodIndex.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.PeriodIndex.to_timestamp   PeriodIndex.to_timestamp(freq=None, how='start')[source]

Cast to DatetimeArray/Index.  Parameters

freq:str or DateOffset, optional

Target frequency. The default is ‘D’ for week or longer, ‘S’ otherwise.
how:{‘s’, ‘e’, ‘start’, ‘end’}

Whether to use the start or end of the time period being converted.    Returns
 DatetimeArray/Index


pandas.PeriodIndex.week   propertyPeriodIndex.week

The week ordinal of the year.


pandas.PeriodIndex.weekday   propertyPeriodIndex.weekday

The day of the week with Monday=0, Sunday=6.


pandas.PeriodIndex.weekofyear   propertyPeriodIndex.weekofyear

The week ordinal of the year.


pandas.PeriodIndex.year   propertyPeriodIndex.year

The year of the period.


pandas.pivot   pandas.pivot(data, index=None, columns=None, values=None)[source]

Return reshaped DataFrame organized by given index / column values. Reshape data (produce a “pivot” table) based on column values. Uses unique values from specified index / columns to form axes of the resulting DataFrame. This function does not support data aggregation, multiple values will result in a MultiIndex in the columns. See the User Guide for more on reshaping.  Parameters

data:DataFrame

index:str or object or a list of str, optional

Column to use to make new frame’s index. If None, uses existing index.  Changed in version 1.1.0: Also accept list of index names.
columns:str or object or a list of str

Column to use to make new frame’s columns.  Changed in version 1.1.0: Also accept list of columns names.
values:str, object or a list of the previous, optional

Column(s) to use for populating new frame’s values. If not specified, all remaining columns will be used and the result will have hierarchically indexed columns.    Returns
 DataFrame

Returns reshaped DataFrame.    Raises
 ValueError:

When there are any index, columns combinations with multiple values. DataFrame.pivot_table when you need to aggregate.      See also  DataFrame.pivot_table

Generalization of pivot that can handle duplicate values for one index/column pair.  DataFrame.unstack

Pivot based on the index values instead of a column.  wide_to_long

Wide panel to long format. Less flexible but more user-friendly than melt.    Notes For finer-tuned control, see hierarchical indexing documentation along with the related stack/unstack methods. Examples
>>> df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two',
...                            'two'],
...                    'bar': ['A', 'B', 'C', 'A', 'B', 'C'],
...                    'baz': [1, 2, 3, 4, 5, 6],
...                    'zoo': ['x', 'y', 'z', 'q', 'w', 't']})
>>> df
    foo   bar  baz  zoo
0   one   A    1    x
1   one   B    2    y
2   one   C    3    z
3   two   A    4    q
4   two   B    5    w
5   two   C    6    t

>>> df.pivot(index='foo', columns='bar', values='baz')
bar  A   B   C
foo
one  1   2   3
two  4   5   6

>>> df.pivot(index='foo', columns='bar')['baz']
bar  A   B   C
foo
one  1   2   3
two  4   5   6

>>> df.pivot(index='foo', columns='bar', values=['baz', 'zoo'])
      baz       zoo
bar   A  B  C   A  B  C
foo
one   1  2  3   x  y  z
two   4  5  6   q  w  t
  You could also assign a list of column names or a list of index names.
>>> df = pd.DataFrame({
...        "lev1": [1, 1, 1, 2, 2, 2],
...        "lev2": [1, 1, 2, 1, 1, 2],
...        "lev3": [1, 2, 1, 2, 1, 2],
...        "lev4": [1, 2, 3, 4, 5, 6],
...        "values": [0, 1, 2, 3, 4, 5]})
>>> df
    lev1 lev2 lev3 lev4 values
0   1    1    1    1    0
1   1    1    2    2    1
2   1    2    1    3    2
3   2    1    2    4    3
4   2    1    1    5    4
5   2    2    2    6    5

>>> df.pivot(index="lev1", columns=["lev2", "lev3"],values="values")
lev2    1         2
lev3    1    2    1    2
lev1
1     0.0  1.0  2.0  NaN
2     4.0  3.0  NaN  5.0

>>> df.pivot(index=["lev1", "lev2"], columns=["lev3"],values="values")
      lev3    1    2
lev1  lev2
   1     1  0.0  1.0
         2  2.0  NaN
   2     1  4.0  3.0
         2  NaN  5.0
  A ValueError is raised if there are any duplicates.
>>> df = pd.DataFrame({"foo": ['one', 'one', 'two', 'two'],
...                    "bar": ['A', 'A', 'B', 'C'],
...                    "baz": [1, 2, 3, 4]})
>>> df
   foo bar  baz
0  one   A    1
1  one   A    2
2  two   B    3
3  two   C    4
  Notice that the first two rows are the same for our index and columns arguments.
>>> df.pivot(index='foo', columns='bar', values='baz')
Traceback (most recent call last):
   ...
ValueError: Index contains duplicate entries, cannot reshape


pandas.pivot_table   pandas.pivot_table(data, values=None, index=None, columns=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, margins_name='All', observed=False, sort=True)[source]

Create a spreadsheet-style pivot table as a DataFrame. The levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame.  Parameters

data:DataFrame

values:column to aggregate, optional

index:column, Grouper, array, or list of the previous

If an array is passed, it must be the same length as the data. The list can contain any of the other types (except list). Keys to group by on the pivot table index. If an array is passed, it is being used as the same manner as column values.
columns:column, Grouper, array, or list of the previous

If an array is passed, it must be the same length as the data. The list can contain any of the other types (except list). Keys to group by on the pivot table column. If an array is passed, it is being used as the same manner as column values.
aggfunc:function, list of functions, dict, default numpy.mean

If list of functions passed, the resulting pivot table will have hierarchical columns whose top level are the function names (inferred from the function objects themselves) If dict is passed, the key is column to aggregate and value is function or list of functions.
fill_value:scalar, default None

Value to replace missing values with (in the resulting pivot table, after aggregation).
margins:bool, default False

Add all row / columns (e.g. for subtotal / grand totals).
dropna:bool, default True

Do not include columns whose entries are all NaN.
margins_name:str, default ‘All’

Name of the row / column that will contain the totals when margins is True.
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.  Changed in version 0.25.0.
sort:bool, default True

Specifies if the result should be sorted.  New in version 1.3.0.     Returns
 DataFrame

An Excel style pivot table.      See also  DataFrame.pivot

Pivot without aggregation that can handle non-numeric data.  DataFrame.melt

Unpivot a DataFrame from wide to long format, optionally leaving identifiers set.  wide_to_long

Wide panel to long format. Less flexible but more user-friendly than melt.    Examples
>>> df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
...                          "bar", "bar", "bar", "bar"],
...                    "B": ["one", "one", "one", "two", "two",
...                          "one", "one", "two", "two"],
...                    "C": ["small", "large", "large", "small",
...                          "small", "large", "small", "small",
...                          "large"],
...                    "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
...                    "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
>>> df
     A    B      C  D  E
0  foo  one  small  1  2
1  foo  one  large  2  4
2  foo  one  large  2  5
3  foo  two  small  3  5
4  foo  two  small  3  6
5  bar  one  large  4  6
6  bar  one  small  5  8
7  bar  two  small  6  9
8  bar  two  large  7  9
  This first example aggregates values by taking the sum.
>>> table = pd.pivot_table(df, values='D', index=['A', 'B'],
...                     columns=['C'], aggfunc=np.sum)
>>> table
C        large  small
A   B
bar one    4.0    5.0
    two    7.0    6.0
foo one    4.0    1.0
    two    NaN    6.0
  We can also fill missing values using the fill_value parameter.
>>> table = pd.pivot_table(df, values='D', index=['A', 'B'],
...                     columns=['C'], aggfunc=np.sum, fill_value=0)
>>> table
C        large  small
A   B
bar one      4      5
    two      7      6
foo one      4      1
    two      0      6
  The next example aggregates by taking the mean across multiple columns.
>>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],
...                     aggfunc={'D': np.mean,
...                              'E': np.mean})
>>> table
                D         E
A   C
bar large  5.500000  7.500000
    small  5.500000  8.500000
foo large  2.000000  4.500000
    small  2.333333  4.333333
  We can also calculate multiple types of aggregations for any given value column.
>>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],
...                     aggfunc={'D': np.mean,
...                              'E': [min, max, np.mean]})
>>> table
                  D   E
               mean max      mean  min
A   C
bar large  5.500000   9  7.500000    6
    small  5.500000   9  8.500000    8
foo large  2.000000   5  4.500000    4
    small  2.333333   6  4.333333    2


pandas.plotting.andrews_curves   pandas.plotting.andrews_curves(frame, class_column, ax=None, samples=200, color=None, colormap=None, **kwargs)[source]

Generate a matplotlib plot of Andrews curves, for visualising clusters of multivariate data. Andrews curves have the functional form:  f(t) = x_1/sqrt(2) + x_2 sin(t) + x_3 cos(t) +

x_4 sin(2t) + x_5 cos(2t) + …   Where x coefficients correspond to the values of each dimension and t is linearly spaced between -pi and +pi. Each row of frame then corresponds to a single curve.  Parameters

frame:DataFrame

Data to be plotted, preferably normalized to (0.0, 1.0).
class_column:Name of the column containing class names

ax:matplotlib axes object, default None

samples:Number of points to plot in each curve

color:list or tuple, optional

Colors to use for the different classes.
colormap:str or matplotlib colormap object, default None

Colormap to select colors from. If string, load colormap with that name from matplotlib.  **kwargs

Options to pass to matplotlib plotting method.    Returns
 class:matplotlip.axis.Axes

   Examples
>>> df = pd.read_csv(
...     'https://raw.github.com/pandas-dev/'
...     'pandas/main/pandas/tests/io/data/csv/iris.csv'
... )
>>> pd.plotting.andrews_curves(df, 'Name')
<AxesSubplot:title={'center':'width'}>


pandas.plotting.autocorrelation_plot   pandas.plotting.autocorrelation_plot(series, ax=None, **kwargs)[source]

Autocorrelation plot for time series.  Parameters

series:Time series

ax:Matplotlib axis object, optional

**kwargs

Options to pass to matplotlib plotting method.    Returns
 class:matplotlib.axis.Axes

   Examples The horizontal lines in the plot correspond to 95% and 99% confidence bands. The dashed line is 99% confidence band.
>>> spacing = np.linspace(-9 * np.pi, 9 * np.pi, num=1000)
>>> s = pd.Series(0.7 * np.random.rand(1000) + 0.3 * np.sin(spacing))
>>> pd.plotting.autocorrelation_plot(s)
<AxesSubplot:title={'center':'width'}, xlabel='Lag', ylabel='Autocorrelation'>


pandas.plotting.bootstrap_plot   pandas.plotting.bootstrap_plot(series, fig=None, size=50, samples=500, **kwds)[source]

Bootstrap plot on mean, median and mid-range statistics. The bootstrap plot is used to estimate the uncertainty of a statistic by relaying on random sampling with replacement [1]. This function will generate bootstrapping plots for mean, median and mid-range statistics for the given number of samples of the given size.  1
“Bootstrapping (statistics)” in https://en.wikipedia.org/wiki/Bootstrapping_%28statistics%29    Parameters

series:pandas.Series

Series from where to get the samplings for the bootstrapping.
fig:matplotlib.figure.Figure, default None

If given, it will use the fig reference for plotting instead of creating a new one with default parameters.
size:int, default 50

Number of data points to consider during each sampling. It must be less than or equal to the length of the series.
samples:int, default 500

Number of times the bootstrap procedure is performed.  **kwds

Options to pass to matplotlib plotting method.    Returns
 matplotlib.figure.Figure

Matplotlib figure.      See also  DataFrame.plot

Basic plotting for DataFrame objects.  Series.plot

Basic plotting for Series objects.    Examples This example draws a basic bootstrap plot for a Series.
>>> s = pd.Series(np.random.uniform(size=100))
>>> pd.plotting.bootstrap_plot(s)
<Figure size 640x480 with 6 Axes>


pandas.plotting.boxplot   pandas.plotting.boxplot(data, column=None, by=None, ax=None, fontsize=None, rot=0, grid=True, figsize=None, layout=None, return_type=None, **kwargs)[source]

Make a box plot from DataFrame columns. Make a box-and-whisker plot from DataFrame columns, optionally grouped by some other columns. A box plot is a method for graphically depicting groups of numerical data through their quartiles. The box extends from the Q1 to Q3 quartile values of the data, with a line at the median (Q2). The whiskers extend from the edges of box to show the range of the data. By default, they extend no more than 1.5 * IQR (IQR = Q3 - Q1) from the edges of the box, ending at the farthest data point within that interval. Outliers are plotted as separate dots. For further details see Wikipedia’s entry for boxplot.  Parameters

column:str or list of str, optional

Column name or list of names, or vector. Can be any valid input to pandas.DataFrame.groupby().
by:str or array-like, optional

Column in the DataFrame to pandas.DataFrame.groupby(). One box-plot will be done per value of columns in by.
ax:object of class matplotlib.axes.Axes, optional

The matplotlib axes to be used by boxplot.
fontsize:float or str

Tick label font size in points or as a string (e.g., large).
rot:int or float, default 0

The rotation angle of labels (in degrees) with respect to the screen coordinate system.
grid:bool, default True

Setting this to True will show the grid.
figsize:A tuple (width, height) in inches

The size of the figure to create in matplotlib.
layout:tuple (rows, columns), optional

For example, (3, 5) will display the subplots using 3 columns and 5 rows, starting from the top-left.
return_type:{‘axes’, ‘dict’, ‘both’} or None, default ‘axes’

The kind of object to return. The default is axes.  ‘axes’ returns the matplotlib axes the boxplot is drawn on. ‘dict’ returns a dictionary whose values are the matplotlib Lines of the boxplot. ‘both’ returns a namedtuple with the axes and dict.
when grouping with by, a Series mapping columns to return_type is returned. If return_type is None, a NumPy array of axes with the same shape as layout is returned.    **kwargs

All other plotting keyword arguments to be passed to matplotlib.pyplot.boxplot().    Returns
 result

See Notes.      See also  Series.plot.hist

Make a histogram.  matplotlib.pyplot.boxplot

Matplotlib equivalent plot.    Notes The return type depends on the return_type parameter:  ‘axes’ : object of class matplotlib.axes.Axes ‘dict’ : dict of matplotlib.lines.Line2D objects ‘both’ : a namedtuple with structure (ax, lines)  For data grouped with by, return a Series of the above or a numpy array:  Series array (for return_type = None)  Use return_type='dict' when you want to tweak the appearance of the lines after plotting. In this case a dict containing the Lines making up the boxes, caps, fliers, medians, and whiskers is returned. Examples Boxplots can be created for every column in the dataframe by df.boxplot() or indicating the columns to be used:
>>> np.random.seed(1234)
>>> df = pd.DataFrame(np.random.randn(10, 4),
...                   columns=['Col1', 'Col2', 'Col3', 'Col4'])
>>> boxplot = df.boxplot(column=['Col1', 'Col2', 'Col3'])
     Boxplots of variables distributions grouped by the values of a third variable can be created using the option by. For instance:
>>> df = pd.DataFrame(np.random.randn(10, 2),
...                   columns=['Col1', 'Col2'])
>>> df['X'] = pd.Series(['A', 'A', 'A', 'A', 'A',
...                      'B', 'B', 'B', 'B', 'B'])
>>> boxplot = df.boxplot(by='X')
     A list of strings (i.e. ['X', 'Y']) can be passed to boxplot in order to group the data by combination of the variables in the x-axis:
>>> df = pd.DataFrame(np.random.randn(10, 3),
...                   columns=['Col1', 'Col2', 'Col3'])
>>> df['X'] = pd.Series(['A', 'A', 'A', 'A', 'A',
...                      'B', 'B', 'B', 'B', 'B'])
>>> df['Y'] = pd.Series(['A', 'B', 'A', 'B', 'A',
...                      'B', 'A', 'B', 'A', 'B'])
>>> boxplot = df.boxplot(column=['Col1', 'Col2'], by=['X', 'Y'])
     The layout of boxplot can be adjusted giving a tuple to layout:
>>> boxplot = df.boxplot(column=['Col1', 'Col2'], by='X',
...                      layout=(2, 1))
     Additional formatting can be done to the boxplot, like suppressing the grid (grid=False), rotating the labels in the x-axis (i.e. rot=45) or changing the fontsize (i.e. fontsize=15):
>>> boxplot = df.boxplot(grid=False, rot=45, fontsize=15)
     The parameter return_type can be used to select the type of element returned by boxplot. When return_type='axes' is selected, the matplotlib axes on which the boxplot is drawn are returned:
>>> boxplot = df.boxplot(column=['Col1', 'Col2'], return_type='axes')
>>> type(boxplot)
<class 'matplotlib.axes._subplots.AxesSubplot'>
  When grouping with by, a Series mapping columns to return_type is returned:
>>> boxplot = df.boxplot(column=['Col1', 'Col2'], by='X',
...                      return_type='axes')
>>> type(boxplot)
<class 'pandas.core.series.Series'>
  If return_type is None, a NumPy array of axes with the same shape as layout is returned:
>>> boxplot = df.boxplot(column=['Col1', 'Col2'], by='X',
...                      return_type=None)
>>> type(boxplot)
<class 'numpy.ndarray'>


pandas.plotting.deregister_matplotlib_converters   pandas.plotting.deregister_matplotlib_converters()[source]

Remove pandas formatters and converters. Removes the custom converters added by register(). This attempts to set the state of the registry back to the state before pandas registered its own units. Converters for pandas’ own types like Timestamp and Period are removed completely. Converters for types pandas overwrites, like datetime.datetime, are restored to their original value.  See also  register_matplotlib_converters

Register pandas formatters and converters with matplotlib.


pandas.plotting.lag_plot   pandas.plotting.lag_plot(series, lag=1, ax=None, **kwds)[source]

Lag plot for time series.  Parameters

series:Time series

lag:lag of the scatter plot, default 1

ax:Matplotlib axis object, optional

**kwds

Matplotlib scatter method keyword arguments.    Returns
 class:matplotlib.axis.Axes

   Examples Lag plots are most commonly used to look for patterns in time series data. Given the following time series
>>> np.random.seed(5)
>>> x = np.cumsum(np.random.normal(loc=1, scale=5, size=50))
>>> s = pd.Series(x)
>>> s.plot()
<AxesSubplot:xlabel='Midrange'>
     A lag plot with lag=1 returns
>>> pd.plotting.lag_plot(s, lag=1)
<AxesSubplot:xlabel='y(t)', ylabel='y(t + 1)'>


pandas.plotting.parallel_coordinates   pandas.plotting.parallel_coordinates(frame, class_column, cols=None, ax=None, color=None, use_columns=False, xticks=None, colormap=None, axvlines=True, axvlines_kwds=None, sort_labels=False, **kwargs)[source]

Parallel coordinates plotting.  Parameters

frame:DataFrame

class_column:str

Column name containing class names.
cols:list, optional

A list of column names to use.
ax:matplotlib.axis, optional

Matplotlib axis object.
color:list or tuple, optional

Colors to use for the different classes.
use_columns:bool, optional

If true, columns will be used as xticks.
xticks:list or tuple, optional

A list of values to use for xticks.
colormap:str or matplotlib colormap, default None

Colormap to use for line colors.
axvlines:bool, optional

If true, vertical lines will be added at each xtick.
axvlines_kwds:keywords, optional

Options to be passed to axvline method for vertical lines.
sort_labels:bool, default False

Sort class_column labels, useful when assigning colors.  **kwargs

Options to pass to matplotlib plotting method.    Returns
 class:matplotlib.axis.Axes

   Examples
>>> df = pd.read_csv(
...     'https://raw.github.com/pandas-dev/'
...     'pandas/main/pandas/tests/io/data/csv/iris.csv'
... )
>>> pd.plotting.parallel_coordinates(
...     df, 'Name', color=('#556270', '#4ECDC4', '#C7F464')
... )
<AxesSubplot:xlabel='y(t)', ylabel='y(t + 1)'>


pandas.plotting.plot_params   pandas.plotting.plot_params={'xaxis.compat': False}

Stores pandas plotting options. Allows for parameter aliasing so you can just use parameter names that are the same as the plot function parameters, but is stored in a canonical format that makes it easy to breakdown into groups later.


pandas.plotting.radviz   pandas.plotting.radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds)[source]

Plot a multidimensional dataset in 2D. Each Series in the DataFrame is represented as a evenly distributed slice on a circle. Each data point is rendered in the circle according to the value on each Series. Highly correlated Series in the DataFrame are placed closer on the unit circle. RadViz allow to project a N-dimensional data set into a 2D space where the influence of each dimension can be interpreted as a balance between the influence of all dimensions. More info available at the original article describing RadViz.  Parameters

frame:DataFrame

Object holding the data.
class_column:str

Column name containing the name of the data point category.
ax:matplotlib.axes.Axes, optional

A plot instance to which to add the information.
color:list[str] or tuple[str], optional

Assign a color to each category. Example: [‘blue’, ‘green’].
colormap:str or matplotlib.colors.Colormap, default None

Colormap to select colors from. If string, load colormap with that name from matplotlib.  **kwds

Options to pass to matplotlib scatter plotting method.    Returns
 class:matplotlib.axes.Axes

    See also  plotting.andrews_curves

Plot clustering visualization.    Examples
>>> df = pd.DataFrame(
...     {
...         'SepalLength': [6.5, 7.7, 5.1, 5.8, 7.6, 5.0, 5.4, 4.6, 6.7, 4.6],
...         'SepalWidth': [3.0, 3.8, 3.8, 2.7, 3.0, 2.3, 3.0, 3.2, 3.3, 3.6],
...         'PetalLength': [5.5, 6.7, 1.9, 5.1, 6.6, 3.3, 4.5, 1.4, 5.7, 1.0],
...         'PetalWidth': [1.8, 2.2, 0.4, 1.9, 2.1, 1.0, 1.5, 0.2, 2.1, 0.2],
...         'Category': [
...             'virginica',
...             'virginica',
...             'setosa',
...             'virginica',
...             'virginica',
...             'versicolor',
...             'versicolor',
...             'setosa',
...             'virginica',
...             'setosa'
...         ]
...     }
... )
>>> pd.plotting.radviz(df, 'Category')
<AxesSubplot:xlabel='y(t)', ylabel='y(t + 1)'>


pandas.plotting.register_matplotlib_converters   pandas.plotting.register_matplotlib_converters()[source]

Register pandas formatters and converters with matplotlib. This function modifies the global matplotlib.units.registry dictionary. pandas adds custom converters for  pd.Timestamp pd.Period np.datetime64 datetime.datetime datetime.date datetime.time   See also  deregister_matplotlib_converters

Remove pandas formatters and converters.


pandas.plotting.scatter_matrix   pandas.plotting.scatter_matrix(frame, alpha=0.5, figsize=None, ax=None, grid=False, diagonal='hist', marker='.', density_kwds=None, hist_kwds=None, range_padding=0.05, **kwargs)[source]

Draw a matrix of scatter plots.  Parameters

frame:DataFrame

alpha:float, optional

Amount of transparency applied.
figsize:(float,float), optional

A tuple (width, height) in inches.
ax:Matplotlib axis object, optional

grid:bool, optional

Setting this to True will show the grid.
diagonal:{‘hist’, ‘kde’}

Pick between ‘kde’ and ‘hist’ for either Kernel Density Estimation or Histogram plot in the diagonal.
marker:str, optional

Matplotlib marker type, default ‘.’.
density_kwds:keywords

Keyword arguments to be passed to kernel density estimate plot.
hist_kwds:keywords

Keyword arguments to be passed to hist function.
range_padding:float, default 0.05

Relative extension of axis range in x and y with respect to (x_max - x_min) or (y_max - y_min).  **kwargs

Keyword arguments to be passed to scatter function.    Returns
 numpy.ndarray

A matrix of scatter plots.     Examples
>>> df = pd.DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D'])
>>> pd.plotting.scatter_matrix(df, alpha=0.2)
array([[<AxesSubplot:xlabel='A', ylabel='A'>,
    <AxesSubplot:xlabel='B', ylabel='A'>,
    <AxesSubplot:xlabel='C', ylabel='A'>,
    <AxesSubplot:xlabel='D', ylabel='A'>],
   [<AxesSubplot:xlabel='A', ylabel='B'>,
    <AxesSubplot:xlabel='B', ylabel='B'>,
    <AxesSubplot:xlabel='C', ylabel='B'>,
    <AxesSubplot:xlabel='D', ylabel='B'>],
   [<AxesSubplot:xlabel='A', ylabel='C'>,
    <AxesSubplot:xlabel='B', ylabel='C'>,
    <AxesSubplot:xlabel='C', ylabel='C'>,
    <AxesSubplot:xlabel='D', ylabel='C'>],
   [<AxesSubplot:xlabel='A', ylabel='D'>,
    <AxesSubplot:xlabel='B', ylabel='D'>,
    <AxesSubplot:xlabel='C', ylabel='D'>,
    <AxesSubplot:xlabel='D', ylabel='D'>]], dtype=object)


pandas.plotting.table   pandas.plotting.table(ax, data, rowLabels=None, colLabels=None, **kwargs)[source]

Helper function to convert DataFrame and Series to matplotlib.table.  Parameters

ax:Matplotlib axes object

data:DataFrame or Series

Data for table contents.  **kwargs

Keyword arguments to be passed to matplotlib.table.table. If rowLabels or colLabels is not specified, data index or column name will be used.    Returns
 matplotlib table object


pandas.qcut   pandas.qcut(x, q, labels=None, retbins=False, precision=3, duplicates='raise')[source]

Quantile-based discretization function. Discretize variable into equal-sized buckets based on rank or based on sample quantiles. For example 1000 values for 10 quantiles would produce a Categorical object indicating quantile membership for each data point.  Parameters

x:1d ndarray or Series

q:int or list-like of float

Number of quantiles. 10 for deciles, 4 for quartiles, etc. Alternately array of quantiles, e.g. [0, .25, .5, .75, 1.] for quartiles.
labels:array or False, default None

Used as labels for the resulting bins. Must be of the same length as the resulting bins. If False, return only integer indicators of the bins. If True, raises an error.
retbins:bool, optional

Whether to return the (bins, labels) or not. Can be useful if bins is given as a scalar.
precision:int, optional

The precision at which to store and display the bins labels.
duplicates:{default ‘raise’, ‘drop’}, optional

If bin edges are not unique, raise ValueError or drop non-uniques.    Returns

out:Categorical or Series or array of integers if labels is False

The return type (Categorical or Series) depends on the input: a Series of type category if input is a Series else Categorical. Bins are represented as categories when categorical data is returned.
bins:ndarray of floats

Returned only if retbins is True.     Notes Out of bounds values will be NA in the resulting Categorical object Examples
>>> pd.qcut(range(5), 4)
...
[(-0.001, 1.0], (-0.001, 1.0], (1.0, 2.0], (2.0, 3.0], (3.0, 4.0]]
Categories (4, interval[float64, right]): [(-0.001, 1.0] < (1.0, 2.0] ...

>>> pd.qcut(range(5), 3, labels=["good", "medium", "bad"])
...
[good, good, medium, bad, bad]
Categories (3, object): [good < medium < bad]

>>> pd.qcut(range(5), 4, labels=False)
array([0, 0, 1, 2, 3])


pandas.RangeIndex   classpandas.RangeIndex(start=None, stop=None, step=None, dtype=None, copy=False, name=None)[source]

Immutable Index implementing a monotonic integer range. RangeIndex is a memory-saving special case of Int64Index limited to representing monotonic ranges. Using RangeIndex may in some instances improve computing speed. This is the default index type used by DataFrame and Series when no explicit index is provided by the user.  Parameters

start:int (default: 0), range, or other RangeIndex instance

If int and “stop” is not given, interpreted as “stop” instead.
stop:int (default: 0)

step:int (default: 1)

dtype:np.int64

Unused, accepted for homogeneity with other index types.
copy:bool, default False

Unused, accepted for homogeneity with other index types.
name:object, optional

Name to be stored in the index.      See also  Index

The base pandas Index type.  Int64Index

Index of int64 data.    Attributes
start The value of the start parameter (0 if this was not supplied).
stop The value of the stop parameter.
step The value of the step parameter (1 if this was not supplied).    Methods
from_range(data[, name, dtype]) Create RangeIndex from a range object.


pandas.RangeIndex.from_range   classmethodRangeIndex.from_range(data, name=None, dtype=None)[source]

Create RangeIndex from a range object.  Returns
 RangeIndex


pandas.RangeIndex.start   propertyRangeIndex.start

The value of the start parameter (0 if this was not supplied).


pandas.RangeIndex.step   propertyRangeIndex.step

The value of the step parameter (1 if this was not supplied).


pandas.RangeIndex.stop   propertyRangeIndex.stop

The value of the stop parameter.


pandas.read_clipboard   pandas.read_clipboard(sep='\\s+', **kwargs)[source]

Read text from clipboard and pass to read_csv.  Parameters

sep:str, default ‘s+’

A string or regex delimiter. The default of ‘s+’ denotes one or more whitespace characters.  **kwargs

See read_csv for the full argument list.    Returns
 DataFrame

A parsed DataFrame object.


pandas.read_csv   pandas.read_csv(filepath_or_buffer, sep=NoDefault.no_default, delimiter=None, header='infer', names=NoDefault.no_default, index_col=None, usecols=None, squeeze=None, prefix=NoDefault.no_default, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=None, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, cache_dates=True, iterator=False, chunksize=None, compression='infer', thousands=None, decimal='.', lineterminator=None, quotechar='"', quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, encoding_errors='strict', dialect=None, error_bad_lines=None, warn_bad_lines=None, on_bad_lines=None, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None, storage_options=None)[source]

Read a comma-separated values (csv) file into DataFrame. Also supports optionally iterating or breaking of the file into chunks. Additional help can be found in the online docs for IO Tools.  Parameters

filepath_or_buffer:str, path object or file-like object

Any valid string path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, gs, and file. For file URLs, a host is expected. A local file could be: file://localhost/path/to/table.csv. If you want to pass in a path object, pandas accepts any os.PathLike. By file-like object, we refer to objects with a read() method, such as a file handle (e.g. via builtin open function) or StringIO.
sep:str, default ‘,’

Delimiter to use. If sep is None, the C engine cannot automatically detect the separator, but the Python parsing engine can, meaning the latter will be used and automatically detect the separator by Python’s builtin sniffer tool, csv.Sniffer. In addition, separators longer than 1 character and different from '\s+' will be interpreted as regular expressions and will also force the use of the Python parsing engine. Note that regex delimiters are prone to ignoring quoted data. Regex example: '\r\t'.
delimiter:str, default None

Alias for sep.
header:int, list of int, None, default ‘infer’

Row number(s) to use as the column names, and the start of the data. Default behavior is to infer the column names: if no names are passed the behavior is identical to header=0 and column names are inferred from the first line of the file, if column names are passed explicitly then the behavior is identical to header=None. Explicitly pass header=0 to be able to replace existing names. The header can be a list of integers that specify row locations for a multi-index on the columns e.g. [0,1,3]. Intervening rows that are not specified will be skipped (e.g. 2 in this example is skipped). Note that this parameter ignores commented lines and empty lines if skip_blank_lines=True, so header=0 denotes the first line of data rather than the first line of the file.
names:array-like, optional

List of column names to use. If the file contains a header row, then you should explicitly pass header=0 to override the column names. Duplicates in this list are not allowed.
index_col:int, str, sequence of int / str, or False, optional, default None

Column(s) to use as the row labels of the DataFrame, either given as string name or column index. If a sequence of int / str is given, a MultiIndex is used. Note: index_col=False can be used to force pandas to not use the first column as the index, e.g. when you have a malformed file with delimiters at the end of each line.
usecols:list-like or callable, optional

Return a subset of the columns. If list-like, all elements must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in names or inferred from the document header row(s). If names are given, the document header row(s) are not taken into account. For example, a valid list-like usecols parameter would be [0, 1, 2] or ['foo', 'bar', 'baz']. Element order is ignored, so usecols=[0, 1] is the same as [1, 0]. To instantiate a DataFrame from data with element order preserved use pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']] for columns in ['foo', 'bar'] order or pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']] for ['bar', 'foo'] order. If callable, the callable function will be evaluated against the column names, returning names where the callable function evaluates to True. An example of a valid callable argument would be lambda x: x.upper() in
['AAA', 'BBB', 'DDD']. Using this parameter results in much faster parsing time and lower memory usage.
squeeze:bool, default False

If the parsed data only contains one column then return a Series.  Deprecated since version 1.4.0: Append .squeeze("columns") to the call to read_csv to squeeze the data.
prefix:str, optional

Prefix to add to column numbers when no header, e.g. ‘X’ for X0, X1, …  Deprecated since version 1.4.0: Use a list comprehension on the DataFrame’s columns after calling read_csv.
mangle_dupe_cols:bool, default True

Duplicate columns will be specified as ‘X’, ‘X.1’, …’X.N’, rather than ‘X’…’X’. Passing in False will cause data to be overwritten if there are duplicate names in the columns.
dtype:Type name or dict of column -> type, optional

Data type for data or columns. E.g. {‘a’: np.float64, ‘b’: np.int32, ‘c’: ‘Int64’} Use str or object together with suitable na_values settings to preserve and not interpret dtype. If converters are specified, they will be applied INSTEAD of dtype conversion.
engine:{‘c’, ‘python’, ‘pyarrow’}, optional

Parser engine to use. The C and pyarrow engines are faster, while the python engine is currently more feature-complete. Multithreading is currently only supported by the pyarrow engine.  New in version 1.4.0: The “pyarrow” engine was added as an experimental engine, and some features are unsupported, or may not work correctly, with this engine.
converters:dict, optional

Dict of functions for converting values in certain columns. Keys can either be integers or column labels.
true_values:list, optional

Values to consider as True.
false_values:list, optional

Values to consider as False.
skipinitialspace:bool, default False

Skip spaces after delimiter.
skiprows:list-like, int or callable, optional

Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file. If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be lambda x: x in [0, 2].
skipfooter:int, default 0

Number of lines at bottom of file to skip (Unsupported with engine=’c’).
nrows:int, optional

Number of rows of file to read. Useful for reading pieces of large files.
na_values:scalar, str, list-like, or dict, optional

Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values. By default the following values are interpreted as NaN: ‘’, ‘#N/A’, ‘#N/A N/A’, ‘#NA’, ‘-1.#IND’, ‘-1.#QNAN’, ‘-NaN’, ‘-nan’, ‘1.#IND’, ‘1.#QNAN’, ‘<NA>’, ‘N/A’, ‘NA’, ‘NULL’, ‘NaN’, ‘n/a’, ‘nan’, ‘null’.
keep_default_na:bool, default True

Whether or not to include the default NaN values when parsing the data. Depending on whether na_values is passed in, the behavior is as follows:  If keep_default_na is True, and na_values are specified, na_values is appended to the default NaN values used for parsing. If keep_default_na is True, and na_values are not specified, only the default NaN values are used for parsing. If keep_default_na is False, and na_values are specified, only the NaN values specified na_values are used for parsing. If keep_default_na is False, and na_values are not specified, no strings will be parsed as NaN.  Note that if na_filter is passed in as False, the keep_default_na and na_values parameters will be ignored.
na_filter:bool, default True

Detect missing value markers (empty strings and the value of na_values). In data without any NAs, passing na_filter=False can improve the performance of reading a large file.
verbose:bool, default False

Indicate number of NA values placed in non-numeric columns.
skip_blank_lines:bool, default True

If True, skip over blank lines rather than interpreting as NaN values.
parse_dates:bool or list of int or names or list of lists or dict, default False

The behavior is as follows:  boolean. If True -> try parsing the index. list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column. list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column. dict, e.g. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’  If a column or index cannot be represented as an array of datetimes, say because of an unparsable value or a mixture of timezones, the column or index will be returned unaltered as an object data type. For non-standard datetime parsing, use pd.to_datetime after pd.read_csv. To parse an index or column with a mixture of timezones, specify date_parser to be a partially-applied pandas.to_datetime() with utc=True. See Parsing a CSV with mixed timezones for more. Note: A fast-path exists for iso8601-formatted dates.
infer_datetime_format:bool, default False

If True and parse_dates is enabled, pandas will attempt to infer the format of the datetime strings in the columns, and if it can be inferred, switch to a faster method of parsing them. In some cases this can increase the parsing speed by 5-10x.
keep_date_col:bool, default False

If True and parse_dates specifies combining multiple columns then keep the original columns.
date_parser:function, optional

Function to use for converting a sequence of string columns to an array of datetime instances. The default uses dateutil.parser.parser to do the conversion. Pandas will try to call date_parser in three different ways, advancing to the next if an exception occurs: 1) Pass one or more arrays (as defined by parse_dates) as arguments; 2) concatenate (row-wise) the string values from the columns defined by parse_dates into a single array and pass that; and 3) call date_parser once for each row using one or more strings (corresponding to the columns defined by parse_dates) as arguments.
dayfirst:bool, default False

DD/MM format dates, international and European format.
cache_dates:bool, default True

If True, use a cache of unique, converted dates to apply the datetime conversion. May produce significant speed-up when parsing duplicate date strings, especially ones with timezone offsets.  New in version 0.25.0.
iterator:bool, default False

Return TextFileReader object for iteration or getting chunks with get_chunk().  Changed in version 1.2: TextFileReader is a context manager.
chunksize:int, optional

Return TextFileReader object for iteration. See the IO Tools docs for more information on iterator and chunksize.  Changed in version 1.2: TextFileReader is a context manager.
compression:str or dict, default ‘infer’

For on-the-fly decompression of on-disk data. If ‘infer’ and ‘%s’ is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, ‘.xz’, or ‘.zst’ (otherwise no compression). If using ‘zip’, the ZIP file must contain only one data file to be read in. Set to None for no decompression. Can also be a dict with key 'method' set to one of {'zip', 'gzip', 'bz2', 'zstd'} and other key-value pairs are forwarded to zipfile.ZipFile, gzip.GzipFile, bz2.BZ2File, or zstandard.ZstdDecompressor, respectively. As an example, the following could be passed for Zstandard decompression using a custom compression dictionary: compression={'method': 'zstd', 'dict_data': my_compression_dict}.  Changed in version 1.4.0: Zstandard support.
thousands:str, optional

Thousands separator.
decimal:str, default ‘.’

Character to recognize as decimal point (e.g. use ‘,’ for European data).
lineterminator:str (length 1), optional

Character to break file into lines. Only valid with C parser.
quotechar:str (length 1), optional

The character used to denote the start and end of a quoted item. Quoted items can include the delimiter and it will be ignored.
quoting:int or csv.QUOTE_* instance, default 0

Control field quoting behavior per csv.QUOTE_* constants. Use one of QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3).
doublequote:bool, default True

When quotechar is specified and quoting is not QUOTE_NONE, indicate whether or not to interpret two consecutive quotechar elements INSIDE a field as a single quotechar element.
escapechar:str (length 1), optional

One-character string used to escape other characters.
comment:str, optional

Indicates remainder of line should not be parsed. If found at the beginning of a line, the line will be ignored altogether. This parameter must be a single character. Like empty lines (as long as skip_blank_lines=True), fully commented lines are ignored by the parameter header but not by skiprows. For example, if comment='#', parsing #empty\na,b,c\n1,2,3 with header=0 will result in ‘a,b,c’ being treated as the header.
encoding:str, optional

Encoding to use for UTF when reading/writing (ex. ‘utf-8’). List of Python standard encodings .  Changed in version 1.2: When encoding is None, errors="replace" is passed to open(). Otherwise, errors="strict" is passed to open(). This behavior was previously only the case for engine="python".   Changed in version 1.3.0: encoding_errors is a new argument. encoding has no longer an influence on how encoding errors are handled.
encoding_errors:str, optional, default “strict”

How encoding errors are treated. List of possible values .  New in version 1.3.0.
dialect:str or csv.Dialect, optional

If provided, this parameter will override values (default or not) for the following parameters: delimiter, doublequote, escapechar, skipinitialspace, quotechar, and quoting. If it is necessary to override values, a ParserWarning will be issued. See csv.Dialect documentation for more details.
error_bad_lines:bool, optional, default None

Lines with too many fields (e.g. a csv line with too many commas) will by default cause an exception to be raised, and no DataFrame will be returned. If False, then these “bad lines” will be dropped from the DataFrame that is returned.  Deprecated since version 1.3.0: The on_bad_lines parameter should be used instead to specify behavior upon encountering a bad line instead.
warn_bad_lines:bool, optional, default None

If error_bad_lines is False, and warn_bad_lines is True, a warning for each “bad line” will be output.  Deprecated since version 1.3.0: The on_bad_lines parameter should be used instead to specify behavior upon encountering a bad line instead.
on_bad_lines:{‘error’, ‘warn’, ‘skip’} or callable, default ‘error’

Specifies what to do upon encountering a bad line (a line with too many fields). Allowed values are :
 ‘error’, raise an Exception when a bad line is encountered. ‘warn’, raise a warning when a bad line is encountered and skip that line. ‘skip’, skip bad lines without raising or warning when they are encountered.
  New in version 1.3.0:   callable, function with signature (bad_line: list[str]) -> list[str] | None that will process a single bad line. bad_line is a list of strings split by the sep. If the function returns None`, the bad line will be ignored.
If the function returns a new list of strings with more elements than
expected, a ``ParserWarning will be emitted while dropping extra elements. Only supported when engine="python"    New in version 1.4.0.
delim_whitespace:bool, default False

Specifies whether or not whitespace (e.g. ' ' or '    ') will be used as the sep. Equivalent to setting sep='\s+'. If this option is set to True, nothing should be passed in for the delimiter parameter.
low_memory:bool, default True

Internally process the file in chunks, resulting in lower memory use while parsing, but possibly mixed type inference. To ensure no mixed types either set False, or specify the type with the dtype parameter. Note that the entire file is read into a single DataFrame regardless, use the chunksize or iterator parameter to return the data in chunks. (Only valid with C parser).
memory_map:bool, default False

If a filepath is provided for filepath_or_buffer, map the file object directly onto memory and access the data directly from there. Using this option can improve performance because there is no longer any I/O overhead.
float_precision:str, optional

Specifies which converter the C engine should use for floating-point values. The options are None or ‘high’ for the ordinary converter, ‘legacy’ for the original lower precision pandas converter, and ‘round_trip’ for the round-trip converter.  Changed in version 1.2.
storage_options:dict, optional

Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to urllib as header options. For other URLs (e.g. starting with “s3://”, and “gcs://”) the key-value pairs are forwarded to fsspec. Please see fsspec and urllib for more details.  New in version 1.2.     Returns
 DataFrame or TextParser

A comma-separated values (csv) file is returned as two-dimensional data structure with labeled axes.      See also  DataFrame.to_csv

Write DataFrame to a comma-separated values (csv) file.  read_csv

Read a comma-separated values (csv) file into DataFrame.  read_fwf

Read a table of fixed-width formatted lines into DataFrame.    Examples
>>> pd.read_csv('data.csv')


pandas.read_excel   pandas.read_excel(io, sheet_name=0, header=0, names=None, index_col=None, usecols=None, squeeze=None, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, parse_dates=False, date_parser=None, thousands=None, decimal='.', comment=None, skipfooter=0, convert_float=None, mangle_dupe_cols=True, storage_options=None)[source]

Read an Excel file into a pandas DataFrame. Supports xls, xlsx, xlsm, xlsb, odf, ods and odt file extensions read from a local filesystem or URL. Supports an option to read a single sheet or a list of sheets.  Parameters

io:str, bytes, ExcelFile, xlrd.Book, path object, or file-like object

Any valid string path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. A local file could be: file://localhost/path/to/table.xlsx. If you want to pass in a path object, pandas accepts any os.PathLike. By file-like object, we refer to objects with a read() method, such as a file handle (e.g. via builtin open function) or StringIO.
sheet_name:str, int, list, or None, default 0

Strings are used for sheet names. Integers are used in zero-indexed sheet positions (chart sheets do not count as a sheet position). Lists of strings/integers are used to request multiple sheets. Specify None to get all worksheets. Available cases:  Defaults to 0: 1st sheet as a DataFrame 1: 2nd sheet as a DataFrame "Sheet1": Load sheet with name “Sheet1” [0, 1, "Sheet5"]: Load first, second and sheet named “Sheet5” as a dict of DataFrame None: All worksheets.
header:int, list of int, default 0

Row (0-indexed) to use for the column labels of the parsed DataFrame. If a list of integers is passed those row positions will be combined into a MultiIndex. Use None if there is no header.
names:array-like, default None

List of column names to use. If file contains no header row, then you should explicitly pass header=None.
index_col:int, list of int, default None

Column (0-indexed) to use as the row labels of the DataFrame. Pass None if there is no such column. If a list is passed, those columns will be combined into a MultiIndex. If a subset of data is selected with usecols, index_col is based on the subset.
usecols:int, str, list-like, or callable default None

 If None, then parse all columns. If str, then indicates comma separated list of Excel column letters and column ranges (e.g. “A:E” or “A,C,E:F”). Ranges are inclusive of both sides. If list of int, then indicates list of column numbers to be parsed. If list of string, then indicates list of column names to be parsed. If callable, then evaluate each column name against it and parse the column if the callable returns True.  Returns a subset of the columns according to behavior above.
squeeze:bool, default False

If the parsed data only contains one column then return a Series.  Deprecated since version 1.4.0: Append .squeeze("columns") to the call to read_excel to squeeze the data.
dtype:Type name or dict of column -> type, default None

Data type for data or columns. E.g. {‘a’: np.float64, ‘b’: np.int32} Use object to preserve data as stored in Excel and not interpret dtype. If converters are specified, they will be applied INSTEAD of dtype conversion.
engine:str, default None

If io is not a buffer or path, this must be set to identify io. Supported engines: “xlrd”, “openpyxl”, “odf”, “pyxlsb”. Engine compatibility :  “xlrd” supports old-style Excel files (.xls). “openpyxl” supports newer Excel file formats. “odf” supports OpenDocument file formats (.odf, .ods, .odt). “pyxlsb” supports Binary Excel files.   Changed in version 1.2.0: The engine xlrd now only supports old-style .xls files. When engine=None, the following logic will be used to determine the engine:  If path_or_buffer is an OpenDocument format (.odf, .ods, .odt), then odf will be used. Otherwise if path_or_buffer is an xls format, xlrd will be used.
Otherwise if path_or_buffer is in xlsb format, pyxlsb will be used.  New in version 1.3.0.
Otherwise openpyxl will be used.  Changed in version 1.3.0.
converters:dict, default None

Dict of functions for converting values in certain columns. Keys can either be integers or column labels, values are functions that take one input argument, the Excel cell content, and return the transformed content.
true_values:list, default None

Values to consider as True.
false_values:list, default None

Values to consider as False.
skiprows:list-like, int, or callable, optional

Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file. If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be lambda
x: x in [0, 2].
nrows:int, default None

Number of rows to parse.
na_values:scalar, str, list-like, or dict, default None

Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values. By default the following values are interpreted as NaN: ‘’, ‘#N/A’, ‘#N/A N/A’, ‘#NA’, ‘-1.#IND’, ‘-1.#QNAN’, ‘-NaN’, ‘-nan’, ‘1.#IND’, ‘1.#QNAN’, ‘<NA>’, ‘N/A’, ‘NA’, ‘NULL’, ‘NaN’, ‘n/a’, ‘nan’, ‘null’.
keep_default_na:bool, default True

Whether or not to include the default NaN values when parsing the data. Depending on whether na_values is passed in, the behavior is as follows:  If keep_default_na is True, and na_values are specified, na_values is appended to the default NaN values used for parsing. If keep_default_na is True, and na_values are not specified, only the default NaN values are used for parsing. If keep_default_na is False, and na_values are specified, only the NaN values specified na_values are used for parsing. If keep_default_na is False, and na_values are not specified, no strings will be parsed as NaN.  Note that if na_filter is passed in as False, the keep_default_na and na_values parameters will be ignored.
na_filter:bool, default True

Detect missing value markers (empty strings and the value of na_values). In data without any NAs, passing na_filter=False can improve the performance of reading a large file.
verbose:bool, default False

Indicate number of NA values placed in non-numeric columns.
parse_dates:bool, list-like, or dict, default False

The behavior is as follows:  bool. If True -> try parsing the index. list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column. list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column. dict, e.g. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’  If a column or index contains an unparsable date, the entire column or index will be returned unaltered as an object data type. If you don`t want to parse some cells as date just change their type in Excel to “Text”. For non-standard datetime parsing, use pd.to_datetime after pd.read_excel. Note: A fast-path exists for iso8601-formatted dates.
date_parser:function, optional

Function to use for converting a sequence of string columns to an array of datetime instances. The default uses dateutil.parser.parser to do the conversion. Pandas will try to call date_parser in three different ways, advancing to the next if an exception occurs: 1) Pass one or more arrays (as defined by parse_dates) as arguments; 2) concatenate (row-wise) the string values from the columns defined by parse_dates into a single array and pass that; and 3) call date_parser once for each row using one or more strings (corresponding to the columns defined by parse_dates) as arguments.
thousands:str, default None

Thousands separator for parsing string columns to numeric. Note that this parameter is only necessary for columns stored as TEXT in Excel, any numeric columns will automatically be parsed, regardless of display format.
decimal:str, default ‘.’

Character to recognize as decimal point for parsing string columns to numeric. Note that this parameter is only necessary for columns stored as TEXT in Excel, any numeric columns will automatically be parsed, regardless of display format.(e.g. use ‘,’ for European data).  New in version 1.4.0.
comment:str, default None

Comments out remainder of line. Pass a character or characters to this argument to indicate comments in the input file. Any data between the comment string and the end of the current line is ignored.
skipfooter:int, default 0

Rows at the end to skip (0-indexed).
convert_float:bool, default True

Convert integral floats to int (i.e., 1.0 –> 1). If False, all numeric data will be read in as floats: Excel stores all numbers as floats internally.  Deprecated since version 1.3.0: convert_float will be removed in a future version
mangle_dupe_cols:bool, default True

Duplicate columns will be specified as ‘X’, ‘X.1’, …’X.N’, rather than ‘X’…’X’. Passing in False will cause data to be overwritten if there are duplicate names in the columns.
storage_options:dict, optional

Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc., if using a URL that will be parsed by fsspec, e.g., starting “s3://”, “gcs://”. An error will be raised if providing this argument with a local path or a file-like buffer. See the fsspec and backend storage implementation docs for the set of allowed keys and values.  New in version 1.2.0.     Returns
 DataFrame or dict of DataFrames

DataFrame from the passed in Excel file. See notes in sheet_name argument for more information on when a dict of DataFrames is returned.      See also  DataFrame.to_excel

Write DataFrame to an Excel file.  DataFrame.to_csv

Write DataFrame to a comma-separated values (csv) file.  read_csv

Read a comma-separated values (csv) file into DataFrame.  read_fwf

Read a table of fixed-width formatted lines into DataFrame.    Examples The file can be read using the file name as string or an open file object:
>>> pd.read_excel('tmp.xlsx', index_col=0)
       Name  Value
0   string1      1
1   string2      2
2  #Comment      3

>>> pd.read_excel(open('tmp.xlsx', 'rb'),
...               sheet_name='Sheet3')
   Unnamed: 0      Name  Value
0           0   string1      1
1           1   string2      2
2           2  #Comment      3
  Index and header can be specified via the index_col and header arguments
>>> pd.read_excel('tmp.xlsx', index_col=None, header=None)
     0         1      2
0  NaN      Name  Value
1  0.0   string1      1
2  1.0   string2      2
3  2.0  #Comment      3
  Column types are inferred but can be explicitly specified
>>> pd.read_excel('tmp.xlsx', index_col=0,
...               dtype={'Name': str, 'Value': float})
       Name  Value
0   string1    1.0
1   string2    2.0
2  #Comment    3.0
  True, False, and NA values, and thousands separators have defaults, but can be explicitly specified, too. Supply the values you would like as strings or lists of strings!
>>> pd.read_excel('tmp.xlsx', index_col=0,
...               na_values=['string1', 'string2'])
       Name  Value
0       NaN      1
1       NaN      2
2  #Comment      3
  Comment lines in the excel input file can be skipped using the comment kwarg
>>> pd.read_excel('tmp.xlsx', index_col=0, comment='#')
      Name  Value
0  string1    1.0
1  string2    2.0
2     None    NaN


pandas.read_feather   pandas.read_feather(path, columns=None, use_threads=True, storage_options=None)[source]

Load a feather-format object from the file path.  Parameters

path:str, path object, or file-like object

String, path object (implementing os.PathLike[str]), or file-like object implementing a binary read() function. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. A local file could be: file://localhost/path/to/table.feather.
columns:sequence, default None

If not provided, all columns are read.
use_threads:bool, default True

Whether to parallelize reading using multiple threads.
storage_options:dict, optional

Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to urllib as header options. For other URLs (e.g. starting with “s3://”, and “gcs://”) the key-value pairs are forwarded to fsspec. Please see fsspec and urllib for more details.  New in version 1.2.0.     Returns
 type of object stored in file