Pandas-2-2-中文文档-十八-
Pandas 2.2 中文文档(十八)
pandas.notnull
pandas.notnull(obj)
检测类数组对象中的非缺失值。
此函数接受一个标量或类似数组对象,并指示值是否有效(在数值数组中为 NaN
,在对象数组中为 None
或 NaN
,在日期时间类数组中为 NaT
)。
参数:
obj类似数组或对象值
要检查非空或非缺失值的对象。
返回:
布尔值或布尔值数组
对于标量输入,返回一个标量布尔值。对于数组输入,返回一个布尔数组,指示每个对应元素是否有效。
另请参见
isna
pandas.notna 的布尔值取反。
Series.notna
检测 Series 中的有效值。
DataFrame.notna
检测 DataFrame 中的有效值。
Index.notna
检测索引中的有效值。
示例
标量参数(包括字符串)返回一个标量布尔值。
>>> pd.notna('dog')
True
>>> pd.notna(pd.NA)
False
>>> pd.notna(np.nan)
False
ndarrays 生成一个布尔值的 ndarray。
>>> 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]])
对于索引,返回一个布尔值的 ndarray。
>>> 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])
对于 Series 和 DataFrame,返回相同类型,包含布尔值。
>>> 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.to_numeric
原文:
pandas.pydata.org/docs/reference/api/pandas.to_numeric.html
pandas.to_numeric(arg, errors='raise', downcast=None, dtype_backend=_NoDefault.no_default)
将参数转换为数值类型。
默认返回 dtype 为 float64 或 int64,取决于提供的数据。使用 downcast 参数获取其他 dtypes。
请注意,如果传入的数字非常大,则可能会发生精度丢失。由于 ndarray 的内部限制,如果传入小于-9223372036854775808(np.iinfo(np.int64).min)或大于 18446744073709551615(np.iinfo(np.uint64).max)的数字,它们很可能会被转换为浮点数,以便可以存储在 ndarray 中。这些警告同样适用于 Series,因为它在内部利用 ndarray。
参数:
arg标量、列表、元组、1 维数组或 Series
要转换的参数。
错误,默认为‘raise’
-
如果‘raise’,则无效解析将引发异常。
-
如果‘coerce’,则无效解析将设置为 NaN。
-
如果‘ignore’,则无效解析将返回输入。
2.2 版中更改。
“ignore”已被弃用。明确捕获异常。
downcaststr,默认为 None
可以是‘integer’、‘signed’、‘unsigned’或‘float’。如果不是 None,并且数据已成功转换为数值 dtype(或者数据本身就是数值型),则根据以下规则将结果数据降级为可能的最小数值 dtype:
-
‘integer’或‘signed’:最小的有符号整数 dtype(最小值:np.int8)
-
‘unsigned’:最小的无符号整数 dtype(最小值:np.uint8)
-
‘float’:最小的浮点数 dtype(最小值:np.float32)
由于此行为与核心转换为数值值的行为是分开的,因此无论‘errors’输入的值如何,都将显示在降级期间引发的任何错误。
此外,仅当结果数据的 dtype 的大小严格大于要转换为的 dtype 时,才会发生降级,因此如果没有任何检查的 dtype 满足该规范,则不会对数据执行降级。
dtype_backend,默认为‘numpy_nullable’
应用于结果DataFrame
的后端数据类型(仍处于实验阶段)。行为如下:
-
"numpy_nullable"
:返回基于可空 dtype 的DataFrame
(默认)。 -
"pyarrow"
:返回基于 pyarrow 的可空ArrowDtype
DataFrame。
2.0 版中的新功能。
返回:
返回
如果解析成功,则为数值。返回类型取决于输入。如果是 Series,则为 Series,否则为 ndarray。
另请参见
DataFrame.astype
将参数转换为指定的 dtype。
to_datetime
将参数转换为日期时间。
to_timedelta
将参数转换为时间增量。
将 numpy 数组转换为指定类型。
DataFrame.convert_dtypes
转换数据类型。
示例
将单独的系列转换为数字,根据需要进行强制转换
>>> s = pd.Series(['1.0', '2', -3])
>>> pd.to_numeric(s)
0 1.0
1 2.0
2 -3.0
dtype: float64
>>> pd.to_numeric(s, downcast='float')
0 1.0
1 2.0
2 -3.0
dtype: float32
>>> pd.to_numeric(s, downcast='signed')
0 1
1 2
2 -3
dtype: int8
>>> s = pd.Series(['apple', '1.0', '2', -3])
>>> pd.to_numeric(s, errors='coerce')
0 NaN
1 1.0
2 2.0
3 -3.0
dtype: float64
可空整数和浮点数类型的向下转换是支持的:
>>> s = pd.Series([1, 2, 3], dtype="Int64")
>>> pd.to_numeric(s, downcast="integer")
0 1
1 2
2 3
dtype: Int8
>>> s = pd.Series([1.0, 2.1, 3.0], dtype="Float64")
>>> pd.to_numeric(s, downcast="float")
0 1.0
1 2.1
2 3.0
dtype: Float32
pandas.to_datetime
原文:
pandas.pydata.org/docs/reference/api/pandas.to_datetime.html
pandas.to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, utc=False, format=None, exact=_NoDefault.no_default, unit=None, infer_datetime_format=_NoDefault.no_default, origin='unix', cache=True)
将参数转换为日期时间。
此函数将标量、类似数组、Series
或DataFrame
/dict-like 转换为 pandas 日期时间对象。
参数:
argint、float、str、datetime、list、tuple、1 维数组、Series、DataFrame/dict-like
要转换为日期时间的对象。如果提供了一个DataFrame
,则该方法至少期望以下列:"year"
、"month"
、"day"
。列"year"
必须以 4 位数字格式指定。
errors,默认为‘raise’
-
如果是
'raise'
,则无效的解析将引发异常。 -
如果是
'coerce'
,则无效的解析将被设置为NaT
。 -
如果是
'ignore'
,则无效的解析将返回输入。
dayfirstbool,默认为 False
如果 arg 是 str 或类似列表,则指定日期解析顺序。如果True
,则解析日期时以日为先,例如,"10/11/12"
被解析为2012-11-10
。
警告
dayfirst=True
不是严格的,但会倾向于首先解析日期。
yearfirstbool,默认为 False
如果 arg 是 str 或类似列表,则指定日期解析顺序。
-
如果
True
,则解析日期时以年为先,例如,"10/11/12"
被解析为2010-11-12
。 -
如果 dayfirst 和 yearfirst 都为
True
,则 yearfirst 优先(与dateutil
相同)。
警告
yearfirst=True
不是严格的,但会倾向于首先解析年份。
utcbool,默认为 False
控制与时区相关的解析、本地化和转换。
-
如果为
True
,该函数始终返回一个带有时区感知的 UTC 本地化的Timestamp
、Series
或DatetimeIndex
。为此,时区无关的输入将被本地化为 UTC,而时区感知的输入将被转换为 UTC。 -
如果为
False
(默认值),输入将不会被强制转换为 UTC。时区无关的输入将保持无关,而时区感知的输入将保持其时间偏移。对于混合偏移(通常是夏令时),存在限制,请参见示例部分了解详情。
警告
在未来的 pandas 版本中,解析具有混合时区的日期时间将引发错误,除非设置 utc=True。请指定 utc=True 以选择新行为并消除此警告。要创建具���混合偏移和对象 dtype 的 Series,请使用 apply 和 datetime.datetime.strptime。
另请参阅:有关pandas 时区转换和本地化的概述文档。
formatstr,默认为 None
用于解析时间的 strftime,例如"%d/%m/%Y"
。有关更多选择的信息,请参阅strftime 文档,尽管请注意"%f"
将解析到纳秒。您还可以传递:
-
“ISO8601”,解析任何ISO8601时间字符串(不一定是完全相同的格式);
-
“mixed”,为每个元素单独推断格式。这是有风险的,您可能应该与 dayfirst 一起使用。
注意
如果传递了DataFrame
,则格式不起作用。
exact布尔值,默认为 True
控制格式的使用方式:
-
如果
True
,则要求精确的格式匹配。 -
如果为
False
,允许格式在目标字符串的任何位置匹配。
不能与format='ISO8601'
或format='mixed'
一起使用。
unit字符串,默认为'ns'
参数的单位(D、s、ms、us、ns)表示单位,可以是整数或浮点数。这将基于原点。例如,使用unit='ms'
和origin='unix'
,这将计算到 Unix 纪元开始的毫秒数。
infer_datetime_format布尔值,默认为 False
如果为True
且未提供格式,则尝试根据第一个非 NaN 元素推断日期时间字符串的格式,并且如果可以推断出,则切换到更快的解析方法。在某些情况下,这可以将解析速度提高约 5-10 倍。
自版本 2.0.0 起弃用:此参数的严格版本现在是默认值,传递它没有效果。
origin标量,默认为'unix'
定义参考日期。数值将被解析为自此参考日期以来的单位数(由 unit 定义)。
-
如果是'unix'(或 POSIX)时间;origin 设置为 1970-01-01。
-
如果是'julian',单位必须是'D',origin 设置为儒略历的开始。儒略日号
0
分配给从公元前 4713 年 1 月 1 日中午开始的那一天。 -
如果可转换为 Timestamp(Timestamp、dt.datetime、np.datetimt64 或日期字符串),则将 origin 设置为由 origin 标识的 Timestamp。
-
如果是浮点数或整数,origin 是相对于 1970-01-01 的差异(由
unit
参数确定的单位)。
cache布尔值,默认为 True
如果True
,则使用一个唯一的转换日期缓存来应用日期时间转换。当解析重复的日期字符串时,特别是带有时区偏移的日期字符串,可能会显著加快速度。只有在至少有 50 个值时才会使用缓存。超出范围的值会使缓存无法使用,并可能减慢解析速度。
返回:
日期时间
如果解析成功。返回类型取决于输入(括号中的类型对应于无法成功解析时的回退):
-
标量:
Timestamp
(或datetime.datetime
) -
类似数组:
DatetimeIndex
(或包含datetime.datetime
的object
数据类型的Series
) -
Series:
Series
,其数据类型为datetime64
(或包含datetime.datetime
的object
数据类型的Series
) -
DataFrame:
Series
,其数据类型为datetime64
(或包含datetime.datetime
的object
数据类型的Series
)
引发:
ParserError
当解析字符串日期失败时。
ValueError
当发生另一个日期时间转换错误时。例如,当DataFrame
中缺少‘year’、‘month’、‘day’列之一时,或者在混合时间偏移的类似数组中找到一个时区感知的datetime.datetime
,且utc=False
时。
另请参见
DataFrame.astype
将参数转换为指定的数据类型。
to_timedelta
将参数转换为时间差。
convert_dtypes
转换数据类型。
注意事项
支持许多输入类型,并导致不同的输出类型:
-
标量
可以是整数、浮点数、字符串、日期时间对象(来自标准库datetime
模块或numpy
)。在可能的情况下,它们将被转换为Timestamp
,否则它们将被转换为datetime.datetime
。None/NaN/null 标量将被转换为NaT
。 -
array-like
可包含 int、float、str、datetime 对象。在可能的情况下,它们会被转换为DatetimeIndex
,否则它们会被转换为包含datetime.datetime
的Index
,其 dtype 为object
。在两种情况下,None/NaN/null 条目都会被转换为NaT
。 -
Series
在可能的情况下会被转换为具有datetime64
dtype 的Series
,否则它们会被转换为包含datetime.datetime
的object
dtype 的Series
。在两种情况下,None/NaN/null 条目都会被转换为NaT
。 -
DataFrame/dict-like
会被转换为具有datetime64
dtype 的Series
。对于每一行,从组装各个数据框列中创建一个 datetime。列键可以是常见缩写,如 [‘year’, ‘month’, ‘day’, ‘minute’, ‘second’, ‘ms’, ‘us’, ‘ns’]) 或其复数形式。
以下原因导致返回 datetime.datetime
对象(可能在 Index
或具有 object
dtype 的 Series
中)而不是适当的 pandas 指定类型(Timestamp
、DatetimeIndex
或具有 datetime64
dtype 的 Series
):
-
当任何输入元素在
Timestamp.min
之前或在Timestamp.max
之后时,请参阅 时间戳限制。 -
当
utc=False
(默认)且输入为包含混合 naive/aware datetime 或带有混合时间偏移的 array-like 或Series
时。请注意,这种情况经常发生,当时区具有夏令时政策时。在这种情况下,您可能希望使用utc=True
。
示例
处理各种输入格式
从DataFrame
的多列组装日期时间。键可以是常见的缩写,如[‘year’, ‘month’, ‘day’, ‘minute’, ‘second’, ‘ms’, ‘us’, ‘ns’],或者是相同的复数形式
>>> df = pd.DataFrame({'year': [2015, 2016],
... 'month': [2, 3],
... 'day': [4, 5]})
>>> pd.to_datetime(df)
0 2015-02-04
1 2016-03-05
dtype: datetime64[ns]
使用 Unix 纪元时间
>>> pd.to_datetime(1490195805, unit='s')
Timestamp('2017-03-22 15:16:45')
>>> pd.to_datetime(1490195805433502912, unit='ns')
Timestamp('2017-03-22 15:16:45.433502912')
警告
对于浮点参数,可能会发生精度舍入。为了防止意外行为,请使用固定宽度的精确类型。
使用非 Unix 纪元起源
>>> pd.to_datetime([1, 2, 3], unit='D',
... origin=pd.Timestamp('1960-01-01'))
DatetimeIndex(['1960-01-02', '1960-01-03', '1960-01-04'],
dtype='datetime64[ns]', freq=None)
与 strptime 行为的差异
"%f"
将解析直到纳秒。
>>> pd.to_datetime('2018-10-26 12:00:00.0000000011',
... format='%Y-%m-%d %H:%M:%S.%f')
Timestamp('2018-10-26 12:00:00.000000001')
无法转换的日期/时间
传递errors='coerce'
将强制将超出范围的日期转换为NaT
,并强制将非日期(或无法解析的日期)转换为NaT
。
>>> pd.to_datetime('13000101', format='%Y%m%d', errors='coerce')
NaT
时区和时间偏移
默认行为(utc=False
)如下:
- 时区无关的输入被转换为时区无关的
DatetimeIndex
:
>>> pd.to_datetime(['2018-10-26 12:00:00', '2018-10-26 13:00:15'])
DatetimeIndex(['2018-10-26 12:00:00', '2018-10-26 13:00:15'],
dtype='datetime64[ns]', freq=None)
- 具有恒定时间偏移的时区意识输入被转换为时区意识的
DatetimeIndex
:
>>> pd.to_datetime(['2018-10-26 12:00 -0500', '2018-10-26 13:00 -0500'])
DatetimeIndex(['2018-10-26 12:00:00-05:00', '2018-10-26 13:00:00-05:00'],
dtype='datetime64[ns, UTC-05:00]', freq=None)
- 然而,具有混合时间偏移的时区意识输入(例如来自具有夏令时的时区,如欧洲/巴黎)无法成功转换为
DatetimeIndex
。解析具有混合时区的日期时间将显示警告,除非设置 utc=True。如果指定 utc=False,则将显示下面的警告,并返回一个简单的Index
,其中包含datetime.datetime
对象:
>>> pd.to_datetime(['2020-10-25 02:00 +0200',
... '2020-10-25 04:00 +0100'])
FutureWarning: In a future version of pandas, parsing datetimes with mixed
time zones will raise an error unless `utc=True`. Please specify `utc=True`
to opt in to the new behaviour and silence this warning. To create a `Series`
with mixed offsets and `object` dtype, please use `apply` and
`datetime.datetime.strptime`.
Index([2020-10-25 02:00:00+02:00, 2020-10-25 04:00:00+01:00],
dtype='object')
- 一组既有时区意识又有时区无关的输入也会被转换为一个简单的
Index
,其中包含datetime.datetime
对象:
>>> from datetime import datetime
>>> pd.to_datetime(["2020-01-01 01:00:00-01:00",
... datetime(2020, 1, 1, 3, 0)])
FutureWarning: In a future version of pandas, parsing datetimes with mixed
time zones will raise an error unless `utc=True`. Please specify `utc=True`
to opt in to the new behaviour and silence this warning. To create a `Series`
with mixed offsets and `object` dtype, please use `apply` and
`datetime.datetime.strptime`.
Index([2020-01-01 01:00:00-01:00, 2020-01-01 03:00:00], dtype='object')
设置utc=True
可以解决上述大部分问题:
- 时区无关的输入被本地化为 UTC
>>> pd.to_datetime(['2018-10-26 12:00', '2018-10-26 13:00'], utc=True)
DatetimeIndex(['2018-10-26 12:00:00+00:00', '2018-10-26 13:00:00+00:00'],
dtype='datetime64[ns, UTC]', freq=None)
- 时区意识的输入被转换为 UTC 时间(输出表示完全相同的日期时间,但从 UTC 时间偏移+00:00 查看)。
>>> pd.to_datetime(['2018-10-26 12:00 -0530', '2018-10-26 12:00 -0500'],
... utc=True)
DatetimeIndex(['2018-10-26 17:30:00+00:00', '2018-10-26 17:00:00+00:00'],
dtype='datetime64[ns, UTC]', freq=None)
- 输入可以包含字符串或日期时间,上述规则仍然适用
>>> pd.to_datetime(['2018-10-26 12:00', datetime(2020, 1, 1, 18)], utc=True)
DatetimeIndex(['2018-10-26 12:00:00+00:00', '2020-01-01 18:00:00+00:00'],
dtype='datetime64[ns, UTC]', freq=None)
pandas.to_timedelta
原文:
pandas.pydata.org/docs/reference/api/pandas.to_timedelta.html
pandas.to_timedelta(arg, unit=None, errors='raise')
将参数转换为时间差。
时间差是时间的绝对差异,以不同的单位(例如天、小时、分钟、秒)表示。此方法将从已识别的时间差格式/值中将参数转换为 Timedelta 类型。
参数:
argstr、时间差、类似列表或 Series
要转换为时间差的数据。
从 2.0 版本开始更改:带有单位‘M’、‘Y’和‘y’的字符串不代表明确的时间差值,将引发异常。
unitstr,可选
表示数值参数的单位。默认为"ns"
。
可能的值:
-
‘W’
-
‘D’ / ‘days’ / ‘day’
-
‘hours’ / ‘hour’ / ‘hr’ / ‘h’ / ‘H’
-
‘m’ / ‘minute’ / ‘min’ / ‘minutes’ / ‘T’
-
‘s’ / ‘seconds’ / ‘sec’ / ‘second’ / ‘S’
-
‘ms’ / ‘milliseconds’ / ‘millisecond’ / ‘milli’ / ‘millis’ / ‘L’
-
‘us’ / ‘microseconds’ / ‘microsecond’ / ‘micro’ / ‘micros’ / ‘U’
-
‘ns’ / ‘nanoseconds’ / ‘nano’ / ‘nanos’ / ‘nanosecond’ / ‘N’
当 arg 包含字符串且errors="raise"
时,不得指定。
自 2.2.0 版本起弃用:单位‘H’、‘T’、‘S’、‘L’、‘U’和‘N’已被弃用,并将在将来的版本中移除。请使用‘h’、‘min’、‘s’、‘ms’、‘us’和‘ns’代替‘H’、‘T’、‘S’、‘L’、‘U’和‘N’。
errors,默认为‘raise’
-
如果是‘raise’,那么无效的解析将引发异常。
-
如果是‘coerce’,那么无效的解析将被设置为 NaT。
-
如果是‘ignore’,那么无效的解析将返回输入。
返回:
时间差
如果解析成功。返回类型取决于输入:
-
类似列表:timedelta64 数据类型的 TimedeltaIndex
-
系列:timedelta64 数据类型的 Series
-
标量:时间差
另请参阅
DataFrame.astype
将参数转换为指定的数据类型。
to_datetime
将参数转换为日期时间。
convert_dtypes
转换数据类型。
注意
如果精度高于纳秒,对于字符串输入,持续时间的精度将被截断为纳秒。
示例
解析单个字符串为时间差:
>>> pd.to_timedelta('1 days 06:05:01.00003')
Timedelta('1 days 06:05:01.000030')
>>> pd.to_timedelta('15.5us')
Timedelta('0 days 00:00:00.000015500')
解析字符串列表或数组:
>>> pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan'])
TimedeltaIndex(['1 days 06:05:01.000030', '0 days 00:00:00.000015500', NaT],
dtype='timedelta64[ns]', freq=None)
通过指定单位关键字参数转换数字:
>>> pd.to_timedelta(np.arange(5), unit='s')
TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:01', '0 days 00:00:02',
'0 days 00:00:03', '0 days 00:00:04'],
dtype='timedelta64[ns]', freq=None)
>>> pd.to_timedelta(np.arange(5), unit='d')
TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],
dtype='timedelta64[ns]', freq=None)
pandas.date_range
原文:
pandas.pydata.org/docs/reference/api/pandas.date_range.html
pandas.date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, inclusive='both', *, unit=None, **kwargs)
返回一个固定频率的 DatetimeIndex。
返回等间隔时间点的范围(任意两个相邻点之间的差异由给定频率指定),使得它们都满足 start <[=] x <[=] end,其中第一个和最后一个分别是该范围中落在freq
边界上的第一个和最后一个时间点(如果给定为频率字符串),或者对于freq
有效的(如果给定为pandas.tseries.offsets.DateOffset
)。 (如果start
、end
或freq
中的一个确切地没有指定,则可以根据periods
计算缺失的参数,即范围中的时间步数。请参见下面的说明。)
参数:
startstr 或日期时间样式,可选
生成日期的左边界。
endstr 或日期时间样式,可选
生成日期的右边界。
periodsint,可选
要生成的周期数。
freqstr、Timedelta、datetime.timedelta 或 DateOffset,默认为‘D’
频率字符串可以有多个,例如‘5h’。查看这里获取频率别名列表。
tzstr 或 tzinfo,可选
返回本地化的 DatetimeIndex 的时区名称,例如‘Asia/Hong_Kong’。默认情况下,生成的 DatetimeIndex 是时区无关的,除非传递了时区感知的日期时间。
normalizebool,默认为 False
在生成日期范围之前将开始/结束日期标准化为午夜。
namestr,默认为 None
生成的 DatetimeIndex 的名称。
inclusive,默认为“both”
包括边界;是否将每个边界设置为闭合或开放。
在版本 1.4.0 中新增。
unitstr,默认为 None
指定结果的期望分辨率。
在版本 2.0.0 中新增。
**kwargs
用于兼容性。对结果没有影响。
返回:
DatetimeIndex
另请参阅
DatetimeIndex
一个不可变的日期时间容器。
timedelta_range
返回一个固定频率的 TimedeltaIndex。
period_range
返回一个固定频率的 PeriodIndex。
interval_range
返回一个固定频率的 IntervalIndex。
注意
在四个参数start
、end
、periods
和freq
中,必须指定三个。如果省略了freq
,则生成的DatetimeIndex
将在start
和end
之间(两侧均闭合)具有periods
个线性间隔的元素。
欲了解更多关于频率字符串的信息,请查看此链接。
示例
指定值
下面的四个示例生成相同的 DatetimeIndex,但变化了开始、结束和周期的组合。
指定开始和结束,默认为每日频率。
>>> pd.date_range(start='1/1/2018', end='1/08/2018')
DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',
'2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],
dtype='datetime64[ns]', freq='D')
指定时区感知的开始和结束,默认为每日频率。
>>> pd.date_range(
... start=pd.to_datetime("1/1/2018").tz_localize("Europe/Berlin"),
... end=pd.to_datetime("1/08/2018").tz_localize("Europe/Berlin"),
... )
DatetimeIndex(['2018-01-01 00:00:00+01:00', '2018-01-02 00:00:00+01:00',
'2018-01-03 00:00:00+01:00', '2018-01-04 00:00:00+01:00',
'2018-01-05 00:00:00+01:00', '2018-01-06 00:00:00+01:00',
'2018-01-07 00:00:00+01:00', '2018-01-08 00:00:00+01:00'],
dtype='datetime64[ns, Europe/Berlin]', freq='D')
指定开始和周期,周期数(天数)。
>>> pd.date_range(start='1/1/2018', periods=8)
DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',
'2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],
dtype='datetime64[ns]', freq='D')
指定结束和周期,周期数(天数)。
>>> pd.date_range(end='1/1/2018', periods=8)
DatetimeIndex(['2017-12-25', '2017-12-26', '2017-12-27', '2017-12-28',
'2017-12-29', '2017-12-30', '2017-12-31', '2018-01-01'],
dtype='datetime64[ns]', freq='D')
指定开始、结束和周期;频率将自动生成(线性间隔)。
>>> pd.date_range(start='2018-04-24', end='2018-04-27', periods=3)
DatetimeIndex(['2018-04-24 00:00:00', '2018-04-25 12:00:00',
'2018-04-27 00:00:00'],
dtype='datetime64[ns]', freq=None)
其他参数
将 freq(频率)更改为 'ME'
(月末频率)。
>>> pd.date_range(start='1/1/2018', periods=5, freq='ME')
DatetimeIndex(['2018-01-31', '2018-02-28', '2018-03-31', '2018-04-30',
'2018-05-31'],
dtype='datetime64[ns]', freq='ME')
允许使用倍数。
>>> pd.date_range(start='1/1/2018', periods=5, freq='3ME')
DatetimeIndex(['2018-01-31', '2018-04-30', '2018-07-31', '2018-10-31',
'2019-01-31'],
dtype='datetime64[ns]', freq='3ME')
freq 也可以指定为一个 Offset 对象。
>>> pd.date_range(start='1/1/2018', periods=5, freq=pd.offsets.MonthEnd(3))
DatetimeIndex(['2018-01-31', '2018-04-30', '2018-07-31', '2018-10-31',
'2019-01-31'],
dtype='datetime64[ns]', freq='3ME')
指定时区以设置时区。
>>> pd.date_range(start='1/1/2018', periods=5, tz='Asia/Tokyo')
DatetimeIndex(['2018-01-01 00:00:00+09:00', '2018-01-02 00:00:00+09:00',
'2018-01-03 00:00:00+09:00', '2018-01-04 00:00:00+09:00',
'2018-01-05 00:00:00+09:00'],
dtype='datetime64[ns, Asia/Tokyo]', freq='D')
inclusive 控制是否包括位于边界上的开始和结束。默认值“both”包括两端的边界点。
>>> pd.date_range(start='2017-01-01', end='2017-01-04', inclusive="both")
DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04'],
dtype='datetime64[ns]', freq='D')
使用 inclusive='left'
来排除结束如果它在边界上的情况。
>>> pd.date_range(start='2017-01-01', end='2017-01-04', inclusive='left')
DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03'],
dtype='datetime64[ns]', freq='D')
使用 inclusive='right'
来排除开始如果它在边界上的情况,类似地,inclusive='neither'
将同时排除开始和结束。
>>> pd.date_range(start='2017-01-01', end='2017-01-04', inclusive='right')
DatetimeIndex(['2017-01-02', '2017-01-03', '2017-01-04'],
dtype='datetime64[ns]', freq='D')
指定单位
>>> pd.date_range(start="2017-01-01", periods=10, freq="100YS", unit="s")
DatetimeIndex(['2017-01-01', '2117-01-01', '2217-01-01', '2317-01-01',
'2417-01-01', '2517-01-01', '2617-01-01', '2717-01-01',
'2817-01-01', '2917-01-01'],
dtype='datetime64[s]', freq='100YS-JAN')
pandas.bdate_range
原文:
pandas.pydata.org/docs/reference/api/pandas.bdate_range.html
pandas.bdate_range(start=None, end=None, periods=None, freq='B', tz=None, normalize=True, name=None, weekmask=None, holidays=None, inclusive='both', **kwargs)
返回一个以工作日为默认的固定频率 DatetimeIndex。
参数:
start字符串或类似 datetime 的对象,默认为 None
生成日期的左边界。
end字符串或类似 datetime 的对象,默认为 None
生成日期的右边界。
periods整数,默认为 None
要生成的周期数。
freq字符串,Timedelta,datetime.timedelta 或 DateOffset,默认为‘B’
频率字符串可以有多个,例如‘5h’。默认为工作日(‘B’)。
tz字符串或 None
返回本地化 DatetimeIndex 的时区名称,例如 Asia/Beijing。
normalize布尔值,默认为 False
在生成日期范围之前,将开始/结束日期标准化为午夜。
name字符串,默认为 None
结果 DatetimeIndex 的名称。
weekmask字符串或 None,默认为 None
有效工作日的周掩码,传递给numpy.busdaycalendar
,仅在传递自定义频率字符串时使用。默认值 None 等同于‘Mon Tue Wed Thu Fri’。
holidays列表或 None,默认为 None
要从有效工作日集中排除的日期,传递给numpy.busdaycalendar
,仅在传递自定义频率字符串时使用。
inclusive,默认为“both”
包括边界;是否将每个边界设置为闭合或开放。
版本 1.4.0 中的新功能。
**kwargs
为了兼容性。对结果没有影响。
返回:
DatetimeIndex
注意
在四个参数中:start
、end
、periods
和freq
,必须指定三个。对于bdate_range
,指定freq
是必需的。如果不希望指定freq
,请使用date_range
。
要了解更多关于频率字符串的信息,请查看此链接。
示例
注意结果中如何跳过两个周末日。
>>> pd.bdate_range(start='1/1/2018', end='1/08/2018')
DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',
'2018-01-05', '2018-01-08'],
dtype='datetime64[ns]', freq='B')
pandas.period_range
原文:
pandas.pydata.org/docs/reference/api/pandas.period_range.html
pandas.period_range(start=None, end=None, periods=None, freq=None, name=None)
返回一个固定频率的 PeriodIndex。
默认频率为日历日。
参数:
startstr、datetime、date、pandas.Timestamp 或 period-like,默认为 None
生成周期的左边界。
endstr、datetime、date、pandas.Timestamp 或 period-like,默认为 None
生成周期的右边界。
periodsint,默认为 None
要生成的周期数。
freqstr 或 DateOffset,可选
频率别名。 默认情况下,如果 start
或 end
是 Period 对象,则从中获取 freq。 否则,默认为每日频率 "D"
。
namestr,默认为 None
结果 PeriodIndex 的名称。
返回:
PeriodIndex
注意事项
在三个参数 start
、end
和 periods
中,必须指定两个。
要了解更多有关频率字符串的信息,请参阅此链接。
示例
>>> 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]')
如果 start
或 end
是 Period
对象,则它们将用作与 period_range
构造函数匹配频率的锚定端点的 PeriodIndex
。
>>> 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.timedelta_range
原文:
pandas.pydata.org/docs/reference/api/pandas.timedelta_range.html
pandas.timedelta_range(start=None, end=None, periods=None, freq=None, name=None, closed=None, *, unit=None)
返回一个以天为默认值的固定频率 TimedeltaIndex。
参数:
startstr 或类似时间增量,默认为 None
生成时间增量的左边界。
endstr 或类似时间增量,默认为 None
生成时间增量的右边界。
periodsint,默认为 None
要生成的周期数。
freqstr、Timedelta、datetime.timedelta 或 DateOffset,默认为‘D’
频率字符串可以有多个,例如‘5h’。
namestr,默认为 None
结果 TimedeltaIndex 的名称。
closedstr,默认为 None
使间隔相对于给定频率在‘左’、‘右’或两侧(None)上闭合。
unitstr,默认为 None
指定结果的所需分辨率。
在 2.0.0 版本中新增。
返回:
TimedeltaIndex
注意
在四个参数start
、end
、periods
和freq
中,必须指定三个。如果省略freq
,则生成的TimedeltaIndex
将在start
和end
之间(两侧都闭合)具有periods
个线性间隔的元素。
要了解更多关于频率字符串的信息,请参见此链接。
示例
>>> pd.timedelta_range(start='1 day', periods=4)
TimedeltaIndex(['1 days', '2 days', '3 days', '4 days'],
dtype='timedelta64[ns]', freq='D')
closed
参数指定包含哪个端点。默认行为是包含两个端点。
>>> pd.timedelta_range(start='1 day', periods=4, closed='right')
TimedeltaIndex(['2 days', '3 days', '4 days'],
dtype='timedelta64[ns]', freq='D')
freq
参数指定 TimedeltaIndex 的频率。只能传递固定频率,非固定频率如‘M’(月末)会引发错误。
>>> pd.timedelta_range(start='1 day', end='2 days', freq='6h')
TimedeltaIndex(['1 days 00:00:00', '1 days 06:00:00', '1 days 12:00:00',
'1 days 18:00:00', '2 days 00:00:00'],
dtype='timedelta64[ns]', freq='6h')
指定start
、end
和periods
;频率将自动生成(线性间隔)。
>>> pd.timedelta_range(start='1 day', end='5 days', periods=4)
TimedeltaIndex(['1 days 00:00:00', '2 days 08:00:00', '3 days 16:00:00',
'5 days 00:00:00'],
dtype='timedelta64[ns]', freq=None)
指定一个单位
>>> pd.timedelta_range("1 Day", periods=3, freq="100000D", unit="s")
TimedeltaIndex(['1 days', '100001 days', '200001 days'],
dtype='timedelta64[s]', freq='100000D')
pandas.infer_freq
原文:
pandas.pydata.org/docs/reference/api/pandas.infer_freq.html
pandas.infer_freq(index)
推断给定输入索引的最可能频率。
参数:
索引:DatetimeIndex、TimedeltaIndex、Series 或者类似数组
如果传递了一个 Series,将使用该系列的值(而不是索引)。
返回:
字符串或者 None
如果没有明显的频率,则为 None。
引发:
TypeError
如果索引不是类似于日期时间的。
ValueError
如果值少于三个。
示例
>>> idx = pd.date_range(start='2020/12/01', end='2020/12/30', periods=30)
>>> pd.infer_freq(idx)
'D'
pandas.interval_range
原文:
pandas.pydata.org/docs/reference/api/pandas.interval_range.html
pandas.interval_range(start=None, end=None, periods=None, freq=None, name=None, closed='right')
返回一个固定频率的 IntervalIndex。
参数:
start数值或类似日期时间,默认为 None
生成区间的左边界。
end数值或类似日期时间,默认为 None
生成区间的右边界。
periodsint,默认为 None
要生成的周期数。
freq数值、字符串、Timedelta、datetime.timedelta 或 DateOffset,默认为 None
每个区间的长度。必须与 start 和 end 的类型一致,例如数值为 2,或者类似日期时间为‘5H’。数值类型默认为 1,类似日期时间默认为‘D’。
name字符串,默认为 None
结果 IntervalIndex 的名称。
closed,默认为‘right’
区间是在左侧、右侧、两侧还是无一侧闭合。
返回:
区间索引
另请参阅
IntervalIndex
一个在同一侧都是闭合的区间索引。
注意
四个参数start
、end
、periods
和freq
中,必须指定三个。如果省略了freq
,则生成的IntervalIndex
将在start
和end
之间(包括两端)均匀间隔periods
个元素。
要了解更多关于类似日期时间频率字符串的信息,请参阅此链接。
示例
支持数值类型的start
和end
。
>>> pd.interval_range(start=0, end=5)
IntervalIndex([(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]],
dtype='interval[int64, right]')
此外,也支持类似日期时间的输入。
>>> pd.interval_range(start=pd.Timestamp('2017-01-01'),
... end=pd.Timestamp('2017-01-04'))
IntervalIndex([(2017-01-01 00:00:00, 2017-01-02 00:00:00],
(2017-01-02 00:00:00, 2017-01-03 00:00:00],
(2017-01-03 00:00:00, 2017-01-04 00:00:00]],
dtype='interval[datetime64[ns], right]')
freq
参数指定 IntervalIndex 内各个区间的左右端点之间的频率。对于数值类型的start
和end
,频率也必须是数值类型。
>>> pd.interval_range(start=0, periods=4, freq=1.5)
IntervalIndex([(0.0, 1.5], (1.5, 3.0], (3.0, 4.5], (4.5, 6.0]],
dtype='interval[float64, right]')
同样,对于类似日期时间的start
和end
,频率必须可以转换为 DateOffset。
>>> pd.interval_range(start=pd.Timestamp('2017-01-01'),
... periods=3, freq='MS')
IntervalIndex([(2017-01-01 00:00:00, 2017-02-01 00:00:00],
(2017-02-01 00:00:00, 2017-03-01 00:00:00],
(2017-03-01 00:00:00, 2017-04-01 00:00:00]],
dtype='interval[datetime64[ns], right]')
指定start
、end
和periods
;频率将自动生成(均匀间隔)。
>>> pd.interval_range(start=0, end=6, periods=4)
IntervalIndex([(0.0, 1.5], (1.5, 3.0], (3.0, 4.5], (4.5, 6.0]],
dtype='interval[float64, right]')
closed
参数指定 IntervalIndex 内各个区间的端点是闭合的哪一侧。
>>> pd.interval_range(end=5, periods=4, closed='both')
IntervalIndex([[1, 2], [2, 3], [3, 4], [4, 5]],
dtype='interval[int64, both]')
pandas.eval
pandas.eval(expr, parser='pandas', engine=None, local_dict=None, global_dict=None, resolvers=(), level=0, target=None, inplace=False)
使用不同后端以字符串形式评估 Python 表达式。
支持以下算术运算:+
、-
、*
、/
、**
、%
、//
(仅限 python 引擎),以及以下布尔运算:|
(或)、&
(与)和 ~
(非)。此外,'pandas' 解析器允许使用 and
、or
和 not
,其语义与相应的位运算符相同。支持 Series
和 DataFrame
对象,并且表现方式与普通的 Python 评估相同。
参数:
exprstr
要评估的表达式。此字符串不能包含任何 Python 语句,只能包含 Python 表达式。
parser,默认为 ‘pandas’
用于从表达式构造语法树的解析器。默认值为 'pandas'
,与标准 Python 稍有不同。或者,您可以使用 'python'
解析器解析表达式以保留严格的 Python 语义。有关更多详细信息,请参阅增强性能文档。
engine��默认为 ‘numexpr’
用于评估表达式的引擎。支持的引擎有
-
None:尝试使用
numexpr
,如果失败则退回到python
-
'numexpr'
:此默认引擎使用 numexpr 评估 pandas 对象,可大幅提高具有大型帧的复杂表达式的速度。 -
'python'
:执行操作,就好像在顶层 Python 中执行了eval
。此引擎通常不太有用。
未来可能会提供更多后端。
local_dictdict 或 None,可选
本地变量字典,默认为 locals()。
global_dictdict 或 None,可选
全局变量字典,默认为 globals()。
resolversdict-like 列表或 None,可选
一个实现 __getitem__
特殊方法的对象列表,您可以使用它们来注入额外的命名空间集合,以用于变量查找。例如,在 query()
方法中使用它来注入 DataFrame.index
和 DataFrame.columns
变量,这些变量分别指代它们各自的 DataFrame
实例属性。
levelint,可选
要遍历并添加到当前作用域的先前堆栈帧数。大多数用户不需要更改此参数。
目标对象,可选,默认为 None
这是用于赋值的目标对象。当表达式中有变量赋值时使用。如果是这样,那么目标必须支持使用字符串键进行项目分配,并且如果返回一个副本,则它还必须支持.copy()
。
inplace布尔值,默认为 False
如果提供了目标对象,并且表达式会改变目标对象,则决定是否就地修改目标对象。否则,返回带有变异的目标对象的副本。
返回:
ndarray、数值标量、DataFrame、Series 或 None
评估给定代码的完成值,如果inplace=True
则为 None。
引发:
ValueError
有许多情况会引发此类错误:
-
目标为 None,但表达式是多行的。
-
表达式是多行的,但并非所有都有项目分配。一个这样排列的示例是:
a = b + 1 a + 2
这里有不同行上的表达式,使其成为多行,但最后一行没有将 a + 2 的输出分配给任何变量。
-
inplace=True,但表达式缺少项目分配。
-
提供了项目分配,但目标不支持字符串项目分配。
-
提供了项目分配且 inplace=False,但目标不支持
.copy()
方法
另请参见
DataFrame.query
评估布尔表达式以查询帧的列。
DataFrame.eval
评估描述 DataFrame 列操作的字符串。
注意
参与算术%
操作的任何对象的dtype
都会递归转换为float64
。
有关更多详细信息,请参阅提高性能文档。
示例
>>> df = pd.DataFrame({"animal": ["dog", "pig"], "age": [10, 20]})
>>> df
animal age
0 dog 10
1 pig 20
我们可以使用pd.eval
添加一个新列:
>>> pd.eval("double_age = df.age * 2", target=df)
animal age double_age
0 dog 10 20
1 pig 20 40
pandas.tseries.api.guess_datetime_format
原文:
pandas.pydata.org/docs/reference/api/pandas.tseries.api.guess_datetime_format.html
pandas.tseries.api.guess_datetime_format(dt_str, dayfirst=False)
猜测给定日期时间字符串的日期时间格式。
参数:
dt_strstr
要猜测格式的日期时间字符串。
dayfirstbool,默认为 False
如果为 True,则解析日期时以日期为首,例如 20/01/2005
警告
dayfirst=True 不是严格的,但会倾向于首先解析日期(这是一个已知的 bug)。
返回:
str or Noneret
日期时间格式字符串(用于 strftime 或 strptime),如果无法猜测则为 None。
示例
>>> from pandas.tseries.api import guess_datetime_format
>>> guess_datetime_format('09/13/2023')
'%m/%d/%Y'
>>> guess_datetime_format('2023|September|13')
pandas.util.hash_array
原文:
pandas.pydata.org/docs/reference/api/pandas.util.hash_array.html
pandas.util.hash_array(vals, encoding='utf8', hash_key='0123456789123456', categorize=True)
给定一个一维数组,返回一个确定性整数数组。
参数:
valsndarray 或 ExtensionArray
encodingstr,默认为'utf8'
字符串数据和键的编码。
hash_keystr,默认为 _default_hash_key
用于编码字符串键的哈希键。
categorizebool,默认为 True
是否在哈希之前先对对象数组进行分类。当数组包含重复值时,这样做更有效率。
返回值:
ndarray[np.uint64, ndim=1]
哈希值,与 vals 长度相同。
示例
>>> pd.util.hash_array(np.array([1, 2, 3]))
array([ 6238072747940578789, 15839785061582574730, 2185194620014831856],
dtype=uint64)
pandas.util.hash_pandas_object
原文:
pandas.pydata.org/docs/reference/api/pandas.util.hash_pandas_object.html
pandas.util.hash_pandas_object(obj, index=True, encoding='utf8', hash_key='0123456789123456', categorize=True)
返回一个索引/系列/数据帧的数据哈希。
参数:
obj索引、系列或数据帧
indexbool,默认为 True
在哈希中包含索引(如果是系列/数据帧)。
encodingstr,默认为'utf8'
当字符串时,数据和键的编码。
hash_keystr,默认为 _default_hash_key
用于编码字符串键的哈希键。
categorizebool,默认为 True
是否在哈希之前首先对对象数组进行分类。当数组包含重复值时,这样更有效率。
返回:
与对象长度相同的 uint64 系列
示例
>>> pd.util.hash_pandas_object(pd.Series([1, 2, 3]))
0 14639053686158035780
1 3869563279212530728
2 393322362522515241
dtype: uint64
pandas.api.interchange.from_dataframe
原文:
pandas.pydata.org/docs/reference/api/pandas.api.interchange.from_dataframe.html
pandas.api.interchange.from_dataframe(df, allow_copy=True)
从支持交换协议的任何 DataFrame 构建pd.DataFrame
。
参数:
dfDataFrameXchg
支持交换协议的对象,即 dataframe 方法。
allow_copybool,默认值:True
是否允许复制内存以执行转换(如果为 false,则请求零拷贝方法)。
返回:
pd.DataFrame
示例
>>> df_not_necessarily_pandas = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
>>> interchange_object = df_not_necessarily_pandas.__dataframe__()
>>> interchange_object.column_names()
Index(['A', 'B'], dtype='object')
>>> df_pandas = (pd.api.interchange.from_dataframe
... (interchange_object.select_columns_by_name(['A'])))
>>> df_pandas
A
0 1
1 2
这些方法(column_names
,select_columns_by_name
)应该适用于任何实现交换协议的数据框库。
Series
构造函数
Series ([data, index, dtype, name, copy, ...]) |
具有轴标签(包括时间序列)的一维 ndarray。 |
---|
属性
轴
Series.index |
Series 的索引(轴标签)。 |
---|---|
Series.array |
支持此 Series 或 Index 的数据的 ExtensionArray。 |
Series.values |
返回 Series 作为 ndarray 或者类似 ndarray,取决于 dtype。 |
Series.dtype |
返回底层数据的 dtype 对象。 |
Series.shape |
返回底层数据的形状的元组。 |
Series.nbytes |
返回底层数据中的字节数。 |
Series.ndim |
底层数据的维度数量,根据定义为 1。 |
Series.size |
返回底层数据中的元素数量。 |
Series.T |
返回转置,根据定义是自身。 |
Series.memory_usage ([index, deep]) |
返回 Series 的内存使用情况。 |
Series.hasnans |
如果存在任何 NaN,则返回 True。 |
Series.empty |
指示 Series/DataFrame 是否为空。 |
Series.dtypes |
返回底层数据的 dtype 对象。 |
Series.name |
返回 Series 的名称。 |
Series.flags |
获取与此 pandas 对象关联的属性。 |
Series.set_flags (*[, copy, ...]) |
返回具有更新标志的新对象。 |
转换
Series.astype (dtype[, copy, errors]) |
将 pandas 对象转换为指定的 dtype dtype 。 |
---|---|
Series.convert_dtypes ([infer_objects, ...]) |
使用支持pd.NA 的 dtype 将列转换为最佳可能的 dtype。 |
Series.infer_objects ([copy]) |
尝试为对象列推断更好的 dtype。 |
Series.copy ([deep]) |
复制此对象的索引和数据。 |
Series.bool () |
(已弃用)返回单个元素 Series 或 DataFrame 的布尔值。 |
Series.to_numpy ([dtype, copy, na_value]) |
表示此 Series 或 Index 中的值的 NumPy ndarray。 |
Series.to_period ([freq, copy]) |
将 Series 从 DatetimeIndex 转换为 PeriodIndex。 |
Series.to_timestamp ([freq, how, copy]) |
转换为时间戳的 DatetimeIndex,位于周期的开始。 |
Series.to_list () |
返回值的列表。 |
Series.__array__ ([dtype, copy]) |
将值作为 NumPy 数组返回。 |
索引,迭代
Series.get (key[, default]) |
获取给定键(例如 DataFrame 列)的对象中的项目。 |
---|---|
Series.at |
访问行/列标签对的单个值。 |
Series.iat |
通过整数位置访问行/列对的单个值。 |
Series.loc |
通过标签或布尔数组访问一组行和列。 |
Series.iloc |
(已弃用)基于纯整数位置的索引,按位置选择。 |
Series.__iter__ () |
返回值的迭代器。 |
Series.items () |
惰性地遍历(索引,值)元组。 |
Series.keys () |
返回索引的别名。 |
Series.pop (item) |
返回项目并从系列中删除。 |
Series.item () |
将底层数据的第一个元素作为 Python 标量返回。 |
Series.xs (key[, axis, level, drop_level]) |
从系列/数据框返回横截面。 |
更多关于 .at
, .iat
, .loc
, 和 .iloc
的信息,请参阅索引文档。
二元运算符函数
Series.add (other[, level, fill_value, axis]) |
返回系列和其他元素的加法(二元运算符 add)。 |
---|---|
Series.sub (other[, level, fill_value, axis]) |
返回系列和其他元素的减法(二元运算符 sub)。 |
Series.mul (other[, level, fill_value, axis]) |
返回系列和其他元素的乘法(二元运算符 mul)。 |
Series.div (other[, level, fill_value, axis]) |
返回系列和其他元素的浮点除法(二元运算符 truediv)。 |
Series.truediv (other[, level, fill_value, axis]) |
返回系列和其他元素的浮点除法(二元运算符 truediv)。 |
Series.floordiv (other[, level, fill_value, axis]) |
返回系列和其他元素的整数除法(二元运算符 floordiv)。 |
Series.mod (other[, level, fill_value, axis]) |
返回系列和其他元素的模运算(二元运算符 mod)。 |
Series.pow (other[, level, fill_value, axis]) |
返回系列和其他元素的指数幂运算(二元运算符 pow)。 |
Series.radd (other[, level, fill_value, axis]) |
返回系列和其他元素的加法(二元运算符 radd)。 |
Series.rsub (other[, level, fill_value, axis]) |
返回系列和其他元素的减法(二元运算符 rsub)。 |
Series.rmul (other[, level, fill_value, axis]) |
返回系列和其他元素的乘法(二元运算符 rmul)。 |
Series.rdiv (other[, level, fill_value, axis]) |
返回系列和其他元素的浮点除法(二元运算符 rtruediv)。 |
Series.rtruediv (other[, level, fill_value, axis]) |
返回 Series 和其他的浮点除法,逐元素进行(二元运算符 rtruediv)。 |
Series.rfloordiv (other[, level, fill_value, ...]) |
返回 Series 和其他的整数除法,逐元素进行(二元运算符 rfloordiv)。 |
Series.rmod (other[, level, fill_value, axis]) |
返回 Series 和其他的模运算,逐元素进行(二元运算符 rmod)。 |
Series.rpow (other[, level, fill_value, axis]) |
返回 Series 和其他的指数幂,逐元素进行(二元运算符 rpow)。 |
Series.combine (other, func[, fill_value]) |
根据 func 将 Series 与 Series 或标量组合。 |
Series.combine_first (other) |
用 'other' 中相同位置的值更新空元素。 |
Series.round ([decimals]) |
将 Series 中的每个值四舍五入到给定的小数位数。 |
Series.lt (other[, level, fill_value, axis]) |
返回 Series 和其他的小于关系,逐元素进行(二元运算符 lt)。 |
Series.gt (other[, level, fill_value, axis]) |
返回 Series 和其他的大于关系,逐元素进行(二元运算符 gt)。 |
Series.le (other[, level, fill_value, axis]) |
返回 Series 和其他的小于或等于关系,逐元素进行(二元运算符 le)。 |
Series.ge (other[, level, fill_value, axis]) |
返回 Series 和其他的大于或等于关系,逐元素进行(二元运算符 ge)。 |
Series.ne (other[, level, fill_value, axis]) |
返回 Series 和其他的不等于关系,逐元素进行(二元运算符 ne)。 |
Series.eq (other[, level, fill_value, axis]) |
返回 Series 和其他的等于关系,逐元素进行(二元运算符 eq)。 |
Series.product ([axis, skipna, numeric_only, ...]) |
返回请求轴上值的乘积。 |
Series.dot (other) |
计算 Series 和其他列之间的点积。 |
函数应用、GroupBy 和窗口
Series.apply (func[, convert_dtype, args, by_row]) |
在 Series 的值上调用函数。 |
---|---|
Series.agg ([func, axis]) |
使用一个或多个操作聚合指定轴上的数据。 |
Series.aggregate ([func, axis]) |
使用一个或多个操作聚合指定轴上的数据。 |
Series.transform (func[, axis]) |
对自身调用 func ,产生与自身轴形状相同的 Series。 |
Series.map (arg[, na_action]) |
根据输入的映射或函数映射 Series 的值。 |
Series.groupby ([by, axis, level, as_index, ...]) |
使用映射器或列的 Series 进行分组。 |
Series.rolling (window[, min_periods, ...]) |
提供滚动窗口计算。 |
Series.expanding ([min_periods, axis, method]) |
提供扩展窗口计算。 |
Series.ewm ([com, span, halflife, alpha, ...]) |
提供指数加权 (EW) 计算。 |
Series.pipe (func, *args, **kwargs) |
应用可链式调用的函数,期望 Series 或 DataFrame 作为输入。 |
计算 / 描述统计
Series.abs () |
返回具有每个元素的绝对数值的 Series/DataFrame。 |
---|---|
Series.all ([axis, bool_only, skipna]) |
返回是否所有元素均为 True,可能沿着轴进行计算。 |
Series.any (*[, axis, bool_only, skipna]) |
返回是否有任何元素为 True,可能沿着轴进行计算。 |
Series.autocorr ([lag]) |
计算滞后 N 的自相关。 |
Series.between (left, right[, inclusive]) |
返回等同于 left <= series <= right 的布尔 Series。 |
Series.clip ([lower, upper, axis, inplace]) |
在输入阈值处修剪值。 |
Series.corr (other[, method, min_periods]) |
计算与其他 Series 的相关性,不包括缺失值。 |
Series.count () |
返回 Series 中非 NA/null 观测值的数量。 |
Series.cov (other[, min_periods, ddof]) |
计算与 Series 的协方差,不包括缺失值。 |
Series.cummax ([axis, skipna]) |
返回 DataFrame 或 Series 轴上的累积最大值。 |
Series.cummin ([axis, skipna]) |
返回 DataFrame 或 Series 轴上的累积最小值。 |
Series.cumprod ([axis, skipna]) |
返回 DataFrame 或 Series 轴上的累积乘积。 |
Series.cumsum ([axis, skipna]) |
返回 DataFrame 或 Series 轴上的累积和。 |
Series.describe ([percentiles, include, exclude]) |
生成描述性统计信息。 |
Series.diff ([periods]) |
元素的第一个离散差异。 |
Series.factorize ([sort, use_na_sentinel]) |
将对象编码为枚举类型或分类变量。 |
Series.kurt ([axis, skipna, numeric_only]) |
返回请求轴上的无偏峰度。 |
Series.max ([axis, skipna, numeric_only]) |
返回请求轴上的最大值。 |
Series.mean ([axis, skipna, numeric_only]) |
返回请求轴上的均值。 |
Series.median ([axis, skipna, numeric_only]) |
返回请求轴上的中位数。 |
Series.min ([axis, skipna, numeric_only]) |
返回请求轴上的最小值。 |
Series.mode ([dropna]) |
返回 Series 的众数。 |
Series.nlargest ([n, keep]) |
返回最大的 n 个元素。 |
Series.nsmallest ([n, keep]) |
返回最小的 n 个元素。 |
Series.pct_change ([periods, fill_method, ...]) |
当前元素与先前元素之间的分数变化。 |
Series.prod ([axis, skipna, numeric_only, ...]) |
返回请求轴上的值的乘积。 |
Series.quantile ([q, interpolation]) |
返回给定分位数处的值。 |
Series.rank ([axis, method, numeric_only, ...]) |
沿轴计算数值数据排名(1 到 n)。 |
Series.sem ([axis, skipna, ddof, numeric_only]) |
返回请求轴上的均值的无偏标准误差。 |
Series.skew ([axis, skipna, numeric_only]) |
返回请求轴上的无偏斜度。 |
Series.std ([axis, skipna, ddof, numeric_only]) |
返回请求轴上的样本标准差。 |
Series.sum ([axis, skipna, numeric_only, ...]) |
返回请求轴上的值的总和。 |
Series.var ([axis, skipna, ddof, numeric_only]) |
返回请求轴上的无偏方差。 |
Series.kurtosis ([axis, skipna, numeric_only]) |
返回请求轴上的无偏��度。 |
Series.unique () |
返回 Series 对象的唯一值。 |
Series.nunique ([dropna]) |
返回对象中唯一元素的数量。 |
Series.is_unique |
如果对象中的值是唯一的,则返回布尔值。 |
Series.is_monotonic_increasing |
如果对象中的值单调递增,则返回布尔值。 |
Series.is_monotonic_decreasing |
如果对象中的值单调递减,则返回布尔值。 |
Series.value_counts ([normalize, sort, ...]) |
返回包含唯一值计数的 Series。 |
重新索引/选择/标签操作
Series.align (other[, join, axis, level, ...]) |
使用指定的连接方法在它们的轴上对齐两个对象。 |
---|---|
Series.case_when (caselist) |
替换条件为 True 的值。 |
Series.drop ([labels, axis, index, columns, ...]) |
返回删除指定索引标签的 Series。 |
Series.droplevel (level[, axis]) |
返回删除请求的索引/列级别的 Series/DataFrame。 |
Series.drop_duplicates (*[, keep, inplace, ...]) |
返回删除重复值的 Series。 |
Series.duplicated ([keep]) |
指示重复的 Series 值。 |
Series.equals (other) |
测试两个对象是否包含相同的元素。 |
Series.first (offset) |
(已弃用) 根据日期偏移量选择时间序列数据的初始周期。 |
Series.head ([n]) |
返回前 n 行。 |
Series.idxmax ([axis, skipna]) |
返回最大值的行标签。 |
Series.idxmin ([axis, skipna]) |
返回最小值的行标签。 |
Series.isin (values) |
Series 中的元素是否包含在 values 中。 |
Series.last (offset) |
(已弃用) 根据日期偏移量选择时间序列数据的最终周期。 |
Series.reindex ([index, axis, method, copy, ...]) |
将 Series 调整为具有新索引的对象,并可选择填充逻辑。 |
Series.reindex_like (other[, method, copy, ...]) |
返回具有与其他对象匹配索引的对象。 |
Series.rename ([index, axis, copy, inplace, ...]) |
修改 Series 的索引标签或名称。 |
Series.rename_axis ([mapper, index, axis, ...]) |
为索引或列设置轴的名称。 |
Series.reset_index ([level, drop, name, ...]) |
生成一个重置索引的新 DataFrame 或 Series。 |
Series.sample ([n, frac, replace, weights, ...]) |
从对象的一个轴中返回随机抽样的项目。 |
Series.set_axis (labels, *[, axis, copy]) |
为给定轴分配所需的索引。 |
Series.take (indices[, axis]) |
沿着一个轴返回给定 位置 索引处的元素。 |
Series.tail ([n]) |
返回最后 n 行。 |
Series.truncate ([before, after, axis, copy]) |
截断 Series 或 DataFrame 在某个索引值之前和之后。 |
Series.where (cond[, other, inplace, axis, level]) |
替换条件为 False 的值。 |
Series.mask (cond[, other, inplace, axis, level]) |
替换条件为 True 的值。 |
Series.add_prefix (prefix[, axis]) |
用字符串前缀添加标签。 |
Series.add_suffix (suffix[, axis]) |
用字符串后缀添加标签。 |
Series.filter ([items, like, regex, axis]) |
根据指定的索引标签对数据帧的行或列进行子集筛选。 |
缺失数据处理
Series.backfill (*[, axis, inplace, limit, ...]) |
(已弃用) 使用下一个有效观察值填充 NA/NaN 值。 |
---|---|
Series.bfill (*[, axis, inplace, limit, ...]) |
使用下一个有效观察值填充 NA/NaN 值。 |
Series.dropna (*[, axis, inplace, how, ...]) |
返回一个删除缺失值的新 Series。 |
Series.ffill (*[, axis, inplace, limit, ...]) |
通过将最后一个有效观察结果传播到下一个有效结果来填充 NA/NaN 值。 |
Series.fillna ([value, method, axis, ...]) |
使用指定方法填充 NA/NaN 值。 |
Series.interpolate ([method, axis, limit, ...]) |
使用插值方法填充 NaN 值。 |
Series.isna () |
检测缺失值。 |
Series.isnull () |
Series.isnull 是 Series.isna 的别名。 |
Series.notna () |
检测存在的(非缺失)值。 |
Series.notnull () |
Series.notnull 是 Series.notna 的别名。 |
Series.pad (*[, axis, inplace, limit, downcast]) |
(已弃用) 通过将最后一个有效观察结果传播到下一个有效结果来填充 NA/NaN 值。 |
Series.replace ([to_replace, value, inplace, ...]) |
用 value 替换 to_replace 中给定的值。 |
重塑,排序
Series.argsort ([axis, kind, order, stable]) |
返回将 Series 值排序的整数索引。 |
---|---|
Series.argmin ([axis, skipna]) |
返回 Series 中最小值的整数位置。 |
Series.argmax ([axis, skipna]) |
返回 Series 中最大值的整数位置。 |
Series.reorder_levels (order) |
使用输入顺序重新排列索引级别。 |
Series.sort_values (*[, axis, ascending, ...]) |
按值排序。 |
Series.sort_index (*[, axis, level, ...]) |
按索引标签对 Series 进行排序。 |
Series.swaplevel ([i, j, copy]) |
在 MultiIndex 中交换级别 i 和 j。 |
Series.unstack ([level, fill_value, sort]) |
将具有 MultiIndex 的 Series 解压缩,也称为透视,以生成 DataFrame。 |
Series.explode ([ignore_index]) |
将列表样式的每个元素转换为一行。 |
Series.searchsorted (value[, side, sorter]) |
查找应插入元素以保持顺序的索引。 |
Series.ravel ([order]) |
(已弃用)将扁平化的基础数据返回为 ndarray 或 ExtensionArray。 |
Series.repeat (repeats[, axis]) |
重复 Series 的元素。 |
Series.squeeze ([axis]) |
将 1 维轴对象压缩为标量。 |
Series.view ([dtype]) |
(已弃用)创建 Series 的新视图。 |
合并/比较/连接/合并
Series.compare (other[, align_axis, ...]) |
与另一个 Series 进行比较并显示差异。 |
---|---|
Series.update (other) |
使用传递的 Series 的值就地修改 Series。 |
与时间序列相关
Series.asfreq (freq[, method, how, ...]) |
将时间序列转换为指定频率。 |
---|---|
Series.asof (where[, subset]) |
返回 where 之前没有任何 NaN 的最后一行。 |
Series.shift ([periods, freq, axis, ...]) |
将索引按所需的周期数移动,可选地使用时间频率。 |
Series.first_valid_index () |
返回第一个非 NA 值的索引,如果找不到非 NA 值,则返回 None。 |
Series.last_valid_index () |
返回最后一个非 NA 值的索引,如果找不到非 NA 值,则返回 None。 |
Series.resample (rule[, axis, closed, label, ...]) |
对时间序列数据重新采样。 |
Series.tz_convert (tz[, axis, level, copy]) |
将 tz-aware 轴转换为目标时区。 |
Series.tz_localize (tz[, axis, level, copy, ...]) |
将序列或数据框的 tz-naive 索引本地化到目标时区。 |
Series.at_time (time[, asof, axis]) |
选择一天中特定时间的值(例如,上午 9:30)。 |
Series.between_time (start_time, end_time[, ...]) |
选择一天中特定时间段的值(例如,上午 9:00-9:30)。 |
访问器
pandas 在各种访问器下提供了特定于数据类型的方法。这些是在 Series
中的单独命名空间,仅适用于特定的数据类型。
Series.str |
StringMethods 的别名 |
---|---|
Series.cat |
CategoricalAccessor 的别名 |
Series.dt |
CombinedDatetimelikeProperties 的别名 |
Series.sparse |
SparseAccessor 的别名 |
DataFrame.sparse |
SparseFrameAccessor 的别名 |
Index.str |
StringMethods 的别名 |
数据类型 | 访问器 |
--- | --- |
日期时间、时间差、周期 | dt |
字符串 | str |
分类 | cat |
稀疏 | sparse |
日期时间属性
Series.dt
可以用于访问序列的日期时间值并返回多个属性。这些可以像 Series.dt.<property>
这样访问。
日期时间属性
Series.dt.date |
返回 Python datetime.date 对象的 numpy 数组。 |
---|---|
Series.dt.time |
返回 Python datetime.time 对象的 numpy 数组。 |
Series.dt.timetz |
返回带有时区的 Python datetime.time 对象的 numpy 数组。 |
Series.dt.year |
日期时间的年份。 |
Series.dt.month |
月份,1 代表一月,12 代表十二月。 |
Series.dt.day |
日期时间的天数。 |
Series.dt.hour |
日期时间的小时数。 |
Series.dt.minute |
日期时间的分钟数。 |
Series.dt.second |
日期时间的秒数。 |
Series.dt.microsecond |
日期时间的微秒数。 |
Series.dt.nanosecond |
日期时间的纳秒数。 |
Series.dt.dayofweek |
一周中的星期几,星期一=0,星期日=6。 |
Series.dt.day_of_week |
一周中的星期几,星期一=0,星期日=6。 |
Series.dt.weekday |
一周中的星期几,星期一=0,星期日=6。 |
Series.dt.dayofyear |
年份中的第几天。 |
Series.dt.day_of_year |
年份中的第几天。 |
Series.dt.days_in_month |
月份中的天数。 |
Series.dt.quarter |
日期所在的季度。 |
Series.dt.is_month_start |
指示日期是否是月份的第一天。 |
Series.dt.is_month_end |
指示日期是否是月份的最后一天。 |
Series.dt.is_quarter_start |
指示日期是否是一个季度的第一天。 |
Series.dt.is_quarter_end |
指示日期是否是一个季度的最后一天。 |
Series.dt.is_year_start |
指示日期是否是一年的第一天。 |
Series.dt.is_year_end |
指示日期是否为年末的标志。 |
Series.dt.is_leap_year |
布尔值指示日期是否属于闰年。 |
Series.dt.daysinmonth |
月份中的天数。 |
Series.dt.days_in_month |
月份中的天数。 |
Series.dt.tz |
返回时区。 |
Series.dt.freq |
返回此 PeriodArray 的频率对象。 |
Series.dt.unit |
日期时间方法
Series.dt.isocalendar () |
根据 ISO 8601 标准计算年、周和日。 |
---|---|
Series.dt.to_period (*args, **kwargs) |
在特定频率下转换为 PeriodArray/PeriodIndex。 |
Series.dt.to_pydatetime () |
(已弃用)将数据作为 datetime.datetime 对象数组返回。 |
Series.dt.tz_localize (*args, **kwargs) |
将时区无关的日期时间数组/索引本地化为时区感知的日期时间数组/索引。 |
Series.dt.tz_convert (*args, **kwargs) |
将时区感知的日期时间数组/索引从一个时区转换为另一个时区。 |
Series.dt.normalize (*args, **kwargs) |
将时间转换为午夜。 |
Series.dt.strftime (*args, **kwargs) |
使用指定的日期格式转换为索引。 |
Series.dt.round (*args, **kwargs) |
对数据执行向上取整操作到指定的频率。 |
Series.dt.floor (*args, **kwargs) |
对数据执行向下取整操作到指定的频率。 |
Series.dt.ceil (*args, **kwargs) |
对数据执行向上舍入操作以指定的频率。 |
Series.dt.month_name (*args, **kwargs) |
返回具有指定区域设置的月份名称。 |
Series.dt.day_name (*args, **kwargs) |
返回具有指定区域设置的星期几名称。 |
Series.dt.as_unit (*args, **kwargs) |
时期属性
Series.dt.qyear |
|
---|---|
Series.dt.start_time |
获取周期开始的时间戳。 |
Series.dt.end_time |
获取周期结束的时间戳。 |
时间差属性
Series.dt.days |
每个元素的天数。 |
---|---|
Series.dt.seconds |
每个元素的秒数(大于等于 0 且小于 1 天)。 |
Series.dt.microseconds |
每个元素的微秒数(大于等于 0 且小于 1 秒)。 |
Series.dt.nanoseconds |
每个元素的纳秒数(大于等于 0 且小于 1 微秒)。 |
Series.dt.components |
返回时间差的各个组成部分的 DataFrame。 |
Series.dt.unit |
时间差方法
Series.dt.to_pytimedelta () |
返回一个原生的 datetime.timedelta 对象数组。 |
---|---|
Series.dt.total_seconds (*args, **kwargs) |
返回以秒为单位表示的每个元素的总持续时间。 |
| Series.dt.as_unit
(*args, **kwargs) | | ### 字符串处理
Series.str
可用于访问系列的值作为字符串,并对其应用多种方法。可以像 Series.str.<function/property>
这样访问它们。
Series.str.capitalize |
将 Series/Index 中的字符串转换为大写。 |
---|---|
Series.str.casefold |
将 Series/Index 中的字符串转换为小写。 |
Series.str.cat |
使用给定的分隔符连接 Series/Index 中的字符串。 |
Series.str.center |
在 Series/Index 中的字符串左右两侧填充。 |
Series.str.contains |
测试 Series 或 Index 中的字符串是否包含模式或正则表达式。 |
Series.str.count |
计算 Series/Index 中每个字符串中模式的出现次数。 |
Series.str.decode |
使用指定的编码对 Series/Index 中的字符串进行解码。 |
Series.str.encode |
使用指定的编码对 Series/Index 中的字符串进行编码。 |
Series.str.endswith |
测试每个字符串元素的末尾是否与模式匹配。 |
Series.str.extract |
在 DataFrame 中提取正则表达式 pat 中的捕获组作为列。 |
Series.str.extractall |
在 DataFrame 中提取正则表达式 pat 中的捕获组作为列。 |
Series.str.find |
返回 Series/Index 中每个字符串的最低索引。 |
Series.str.findall |
在 Series/Index 中查找模式或正则表达式的所有匹配项。 |
Series.str.fullmatch |
确定每个字符串是否完全匹配正则表达式。 |
Series.str.get (i) |
从指定位置或指定键提取每个组件的元素。 |
Series.str.index (sub[, start, end]) |
返回系列/索引中每个字符串中最低的索引。 |
Series.str.join (sep) |
使用指定的分隔符连接系列/索引中包含的元素列表。 |
Series.str.len () |
计算系列/索引中每个元素的长度。 |
Series.str.ljust (width[, fillchar]) |
在系列/索引中的字符串右侧填充空格。 |
Series.str.lower () |
将系列/索引中的字符串转换为小写。 |
Series.str.lstrip ([to_strip]) |
删除前导字符。 |
Series.str.match (pat[, case, flags, na]) |
确定每个字符串是否以正则表达式的匹配开头。 |
Series.str.normalize (form) |
返回系列/索引中字符串的 Unicode 规范形式。 |
Series.str.pad (width[, side, fillchar]) |
将系列/索引中的字符串填充到指定宽度。 |
Series.str.partition ([sep, expand]) |
将字符串在第一次出现的分隔符处拆分。 |
Series.str.removeprefix (prefix) |
从对象系列中删除前缀。 |
Series.str.removesuffix (suffix) |
从对象系列中删除后缀。 |
Series.str.repeat (repeats) |
在系列或索引中重复每个字符串。 |
Series.str.replace (pat, repl[, n, case, ...]) |
替换系列/索引中每个出现的模式/正则表达式。 |
Series.str.rfind (sub[, start, end]) |
返回系列/索引中每个字符串中最高的索引。 |
Series.str.rindex (sub[, start, end]) |
返回系列/索引中每个字符串的最高索引。 |
Series.str.rjust (width[, fillchar]) |
在系列/索引中字符串的左侧填充。 |
Series.str.rpartition ([sep, expand]) |
在字符串中最后一次出现的位置分割字符串。 |
Series.str.rstrip ([to_strip]) |
删除字符串末尾的字符。 |
Series.str.slice ([start, stop, step]) |
从系列或索引中的每个元素中切片子字符串。 |
Series.str.slice_replace ([start, stop, repl]) |
用另一个值替换字符串的位置切片。 |
Series.str.split ([pat, n, expand, regex]) |
在给定的分隔符/定界符周围分割字符串。 |
Series.str.rsplit ([pat, n, expand]) |
在给定的分隔符/定界符周围分割字符串。 |
Series.str.startswith (pat[, na]) |
检测每个字符串元素的开头是否匹配某个模式。 |
Series.str.strip ([to_strip]) |
删除字符串的前导和尾随字符。 |
Series.str.swapcase () |
将系列/索引中的字符串进行大小写交换。 |
Series.str.title () |
将系列/索引中的字符串转换为标题格式。 |
Series.str.translate (table) |
通过给定的映射表映射字符串中的所有字符。 |
Series.str.upper () |
将系列/索引中的字符串转换为大写。 |
Series.str.wrap (width, **kwargs) |
将系列/索引中的字符串按指定行宽进行换行。 |
Series.str.zfill (width) |
在系列/索引中的字符串前面填充'0'字符。 |
Series.str.isalnum () |
检查每个字符串中的所有字符是否都是字母数字。 |
Series.str.isalpha () |
检查每个字符串中的所有字符是否都是字母。 |
Series.str.isdigit () |
检查每个字符串中的所有字符是否都是数字。 |
Series.str.isspace () |
检查每个字符串中的所有字符是否都是空格。 |
Series.str.islower () |
检查每个字符串中的所有字符是否都是小写。 |
Series.str.isupper () |
检查每个字符串中的所有字符是否都是大写。 |
Series.str.istitle () |
检查每个字符串中的所有字符是否都是首字母大写。 |
Series.str.isnumeric () |
检查每个字符串中的所有字符是否都是数字。 |
Series.str.isdecimal () |
检查每个字符串中的所有字符是否都是十进制数。 |
| Series.str.get_dummies
([sep]) | 返回 Series 的虚拟/指示变量的 DataFrame。 | ### 分类访问器
分类特定的方法和属性可以在Series.cat
访问器下使用。
Series.cat.categories |
此分类的类别。 |
---|---|
Series.cat.ordered |
类别是否具有有序关系。 |
Series.cat.codes |
返回代码的 Series 以及索引。 |
Series.cat.rename_categories (*args, **kwargs) |
重命名类别。 |
Series.cat.reorder_categories (*args, **kwargs) |
根据 new_categories 指定的顺序重新排序类别。 |
Series.cat.add_categories (*args, **kwargs) |
添加新的类别。 |
Series.cat.remove_categories (*args, **kwargs) |
移除指定的类别。 |
Series.cat.remove_unused_categories (*args, ...) |
移除未使用的类别。 |
Series.cat.set_categories (*args, **kwargs) |
将类别设置为指定的新类别。 |
Series.cat.as_ordered (*args, **kwargs) |
将分类设置为有序。 |
| Series.cat.as_unordered
(*args, **kwargs) | 将分类设置为无序。 | ### 稀疏访问器
稀��-dtype 特定的方法和属性可在 Series.sparse
访问器下找到。
Series.sparse.npoints |
非 fill_value 点的数量。 |
---|---|
Series.sparse.density |
非 fill_value 点的百分比,以小数表示。 |
Series.sparse.fill_value |
数据中的 fill_value 元素不会被存储。 |
Series.sparse.sp_values |
包含非 fill_value 值的 ndarray。 |
Series.sparse.from_coo (A[, dense_index]) |
从 scipy.sparse.coo_matrix 创建具有稀疏值的 Series。 |
| Series.sparse.to_coo
([row_levels, ...]) | 从具有 MultiIndex 的 Series 创建一个 scipy.sparse.coo_matrix。 | ### 列表访问器
列表-dtype 特定的方法和属性可在 Series.list
访问器下找到。
Series.list.flatten () |
展平列表值。 |
---|---|
Series.list.len () |
返回 Series 中每个列表的长度。 |
| Series.list.__getitem__
(key) | 在 Series 中索引或切片列表。 | ### 结构访问器
箭头结构体 dtype 特定方法和属性在Series.struct
访问器下提供。
Series.struct.dtypes |
返回结构体的每个子字段的 dtype 对象。 |
---|---|
Series.struct.field (name_or_index) |
将结构体的子字段提取为 Series。 |
| Series.struct.explode
() | 将结构体的所有子字段提取为 DataFrame。 | ### 标志
标志指的是 pandas 对象的属性。数据集的属性(如记录日期、访问的 URL 等)应存储在Series.attrs
中。
| Flags
(obj, *, allows_duplicate_labels) | 适用于 pandas 对象的标志。 | ### 元数据
Series.attrs
是用于存储此 Series 的全局元数据的字典。
警告
Series.attrs
被视为实验性内容,可能会在没有警告的情况下更改。
Series.attrs |
此数据集的全局属性字典。 |
---|
绘图
Series.plot
既是一个可调用方法,也是特定绘图方法的命名空间属性,形式为Series.plot.<kind>
。
Series.plot ([kind, ax, figsize, ....]) |
Series 绘图访问器和方法 |
---|---|
Series.plot.area ([x, y, stacked]) |
绘制堆叠面积图。 |
Series.plot.bar ([x, y]) |
垂直条形图。 |
Series.plot.barh ([x, y]) |
绘制水平条形图。 |
Series.plot.box ([by]) |
绘制 DataFrame 列的箱线图。 |
Series.plot.density ([bw_method, ind]) |
使用高斯核生成核密度估计图。 |
Series.plot.hist ([by, bins]) |
绘制 DataFrame 列的直方图。 |
Series.plot.kde ([bw_method, ind]) |
使用高斯核生成核密度估计图。 |
Series.plot.line ([x, y]) |
将 Series 或 DataFrame 绘制为折线图。 |
Series.plot.pie (**kwargs) |
生成饼图。 |
Series.hist ([by, ax, grid, xlabelsize, ...]) |
使用 matplotlib 绘制输入 Series 的直方图。 |
序列化 / IO / 转换
Series.to_pickle (path, *[, compression, ...]) |
将对象序列化为文件。 |
---|---|
Series.to_csv ([path_or_buf, sep, na_rep, ...]) |
将对象写入逗号分隔值(csv)文件。 |
Series.to_dict (*[, into]) |
将 Series 转换为 {标签 -> 值} 字典或类似字典的对象。 |
Series.to_excel (excel_writer, *[, ...]) |
将对象写入 Excel 表格。 |
Series.to_frame ([name]) |
将 Series 转换为 DataFrame。 |
Series.to_xarray () |
从 pandas 对象返回一个 xarray 对象。 |
Series.to_hdf (path_or_buf, *, key[, mode, ...]) |
使用 HDFStore 将包含的数据写入 HDF5 文件。 |
Series.to_sql (name, con, *[, schema, ...]) |
将存储在 DataFrame 中的记录写入 SQL 数据库。 |
Series.to_json ([path_or_buf, orient, ...]) |
将对象转换为 JSON 字符串。 |
Series.to_string ([buf, na_rep, ...]) |
呈现 Series 的字符串表示。 |
Series.to_clipboard (*[, excel, sep]) |
将对象复制到系统剪贴板。 |
Series.to_latex ([buf, columns, header, ...]) |
将对象呈现为 LaTeX 表格、长表格或嵌套表格。 |
Series.to_markdown ([buf, mode, index, ...]) |
以 Markdown 友好的格式打印 Series。 |
构造函数
Series ([data, index, dtype, name, copy, ...]) |
具有轴标签的一维 ndarray(包括时间序列)。 |
---|
属性
轴
Series.index |
Series 的索引(轴标签)。 |
---|---|
Series.array |
支持此 Series 或 Index 的数据的 ExtensionArray。 |
Series.values |
根据 dtype 返回 Series 作为 ndarray 或类似 ndarray。 |
Series.dtype |
返回底层数据的 dtype 对象。 |
Series.shape |
返回底层数据的形状的元组。 |
Series.nbytes |
返回底层数据的字节数。 |
Series.ndim |
底层数据的维数,根据定义为 1。 |
Series.size |
返回底层数据中的元素数。 |
Series.T |
返回转置,根据定义是自身。 |
Series.memory_usage ([index, deep]) |
返回 Series 的内存使用情况。 |
Series.hasnans |
如果存在任何 NaN,则返回 True。 |
Series.empty |
指示 Series/DataFrame 是否为空。 |
Series.dtypes |
返回底层数据的 dtype 对象。 |
Series.name |
返回 Series 的名称。 |
Series.flags |
获取与此 pandas 对象关联的属性。 |
Series.set_flags (*[, copy, ...]) |
返回具有更新标志的新对象。 |
转换
Series.astype (dtype[, copy, errors]) |
将 pandas 对象转换为指定的 dtype dtype 。 |
---|---|
Series.convert_dtypes ([infer_objects, ...]) |
使用支持 pd.NA 的 dtype 将列转换为可能的最佳 dtype。 |
Series.infer_objects ([copy]) |
尝试推断对象列的更好数据类型。 |
Series.copy ([deep]) |
复制此对象的索引和数据。 |
Series.bool () |
(已弃用)返回单个元素 Series 或 DataFrame 的布尔值。 |
Series.to_numpy ([dtype, copy, na_value]) |
表示此 Series 或 Index 中的值的 NumPy ndarray。 |
Series.to_period ([freq, copy]) |
将 Series 从 DatetimeIndex 转换为 PeriodIndex。 |
Series.to_timestamp ([freq, how, copy]) |
转换为时间戳的 DatetimeIndex,位于周期的开始。 |
Series.to_list () |
返回值的列表。 |
Series.__array__ ([dtype, copy]) |
将值作为 NumPy 数组返回。 |
索引,迭代
Series.get (key[, default]) |
获取给定键(例如:DataFrame 列)的对象中的项目。 |
---|---|
Series.at |
访问行/列标签对的单个值。 |
Series.iat |
通过整数位置访问行/列对的单个值。 |
Series.loc |
通过标签或布尔数组访问一组行和列。 |
Series.iloc |
(已弃用)基于纯整数位置的按位置选择索引。 |
Series.__iter__ () |
返回值的迭代器。 |
Series.items () |
惰性地遍历(索引,值)元组。 |
Series.keys () |
返回索引的别名。 |
Series.pop (item) |
返回项目并从系列中删除。 |
Series.item () |
将底层数据的第一个元素作为 Python 标量返回。 |
Series.xs (key[, axis, level, drop_level]) |
从系列/数据框中返回横截面。 |
更多关于 .at
, .iat
, .loc
, 和 .iloc
的信息,请参阅索引文档。
二元操作符函数
Series.add (other[, level, fill_value, axis]) |
返回系列和其他的加法,逐元素进行计算(二元操作符 add)。 |
---|---|
Series.sub (other[, level, fill_value, axis]) |
返回系列和其他的减法,逐元素进行计算(二元操作符 sub)。 |
Series.mul (other[, level, fill_value, axis]) |
返回系列和其他的乘法,逐元素进行计算(二元操作符 mul)。 |
Series.div (other[, level, fill_value, axis]) |
返回系列和其他的浮点除法,逐元素进行计算(二元操作符 truediv)。 |
Series.truediv (other[, level, fill_value, axis]) |
返回系列和其他的浮点除法,逐元素进行计算(二元操作符 truediv)。 |
Series.floordiv (other[, level, fill_value, axis]) |
返回系列和其他的整除,逐元素进行计算(二元操作符 floordiv)。 |
Series.mod (other[, level, fill_value, axis]) |
返回系列和其他的模数,逐元素进行计算(二元操作符 mod)。 |
Series.pow (other[, level, fill_value, axis]) |
返回系列和其他的指数幂,逐元素进行计算(二元操作符 pow)。 |
Series.radd (other[, level, fill_value, axis]) |
返回系列和其他的加法,逐元素进行计算(二元操作符 radd)。 |
Series.rsub (other[, level, fill_value, axis]) |
返回系列和其他的减法,逐元素进行计算(二元操作符 rsub)。 |
Series.rmul (other[, level, fill_value, axis]) |
返回系列和其他的乘法,逐元素进行计算(二元操作符 rmul)。 |
Series.rdiv (other[, level, fill_value, axis]) |
返回系列和其他的浮点除法,逐元素进行计算(二元操作符 rtruediv)。 |
Series.rtruediv (other[, level, fill_value, axis]) |
返回 Series 和其他的浮点数除法,逐元素进行计算(二元运算符 rtruediv)。 |
Series.rfloordiv (other[, level, fill_value, ...]) |
返回 Series 和其他的整数除法,逐元素进行计算(二元运算符 rfloordiv)。 |
Series.rmod (other[, level, fill_value, axis]) |
返回 Series 和其他的模数,逐元素进行计算(二元运算符 rmod)。 |
Series.rpow (other[, level, fill_value, axis]) |
返回 Series 和其他的指数幂,逐元素进行计算(二元运算符 rpow)。 |
Series.combine (other, func[, fill_value]) |
根据 func 将 Series 与 Series 或标量组合在一起。 |
Series.combine_first (other) |
使用 'other' 中相同位置的值更新空元素。 |
Series.round ([decimals]) |
将 Series 中的每个值四舍五入到指定的小数位数。 |
Series.lt (other[, level, fill_value, axis]) |
返回 Series 和其他的小于值,逐元素进行比较(二元运算符 lt)。 |
Series.gt (other[, level, fill_value, axis]) |
返回 Series 和其他的大于值,逐元素进行比较(二元运算符 gt)。 |
Series.le (other[, level, fill_value, axis]) |
返回 Series 和其他的小于或等于值,逐元素进行比较(二元运算符 le)。 |
Series.ge (other[, level, fill_value, axis]) |
返回 Series 和其他的大于或等于值,逐元素进行比较(二元运算符 ge)。 |
Series.ne (other[, level, fill_value, axis]) |
返回 Series 和其他的不相等值,逐元素进行比较(二元运算符 ne)。 |
Series.eq (other[, level, fill_value, axis]) |
返回 Series 和其他的相等值,逐元素进行比较(二元运算符 eq)。 |
Series.product ([axis, skipna, numeric_only, ...]) |
返回请求轴上值的乘积。 |
Series.dot (other) |
计算 Series 和其他列之间的点积。 |
函数应用、GroupBy 和窗口
Series.apply (func[, convert_dtype, args, by_row]) |
对 Series 的值调用函数。 |
---|---|
Series.agg ([func, axis]) |
在指定轴上使用一个或多个操作进行聚合。 |
Series.aggregate ([func, axis]) |
在指定轴上使用一个或多个操作进行聚合。 |
Series.transform (func[, axis]) |
在自身上调用 func ,生成一个与自身轴形状相同的 Series。 |
Series.map (arg[, na_action]) |
根据输入映射或函数对 Series 的值进行映射。 |
Series.groupby ([by, axis, level, as_index, ...]) |
使用映射器或一系列列对 Series 进行分组。 |
Series.rolling (window[, min_periods, ...]) |
提供滚动窗口计算。 |
Series.expanding ([min_periods, axis, method]) |
提供扩展窗口计算。 |
Series.ewm ([com, span, halflife, alpha, ...]) |
提供指数加权(EW)计算。 |
Series.pipe (func, *args, **kwargs) |
应用可链式调用的函数,期望 Series 或 DataFrames。 |
计算 / 描述性统计
Series.abs () |
返回每个元素的绝对数值的 Series/DataFrame。 |
---|---|
Series.all ([axis, bool_only, skipna]) |
返回所有元素是否都为 True,可能在一个轴上。 |
Series.any (*[, axis, bool_only, skipna]) |
返回任何元素��否为 True,可能在一个轴上。 |
Series.autocorr ([lag]) |
计算滞后 N 的自相关性。 |
Series.between (left, right[, inclusive]) |
返回布尔 Series,相当于 left <= series <= right。 |
Series.clip ([lower, upper, axis, inplace]) |
在输入阈值处修剪值。 |
Series.corr (other[, method, min_periods]) |
计算与其他 Series 的相关性,排除缺失值。 |
Series.count () |
返回 Series 中非 NA/null 观测值的数量。 |
Series.cov (other[, min_periods, ddof]) |
计算与 Series 的协方差,排除缺失值。 |
Series.cummax ([axis, skipna]) |
返回 DataFrame 或 Series 轴上的累积最大值。 |
Series.cummin ([axis, skipna]) |
返回 DataFrame 或 Series 轴上的累积最小值。 |
Series.cumprod ([axis, skipna]) |
返回 DataFrame 或 Series 轴上的累积乘积。 |
Series.cumsum ([axis, skipna]) |
返回 DataFrame 或 Series 轴上的累积总和。 |
Series.describe ([percentiles, include, exclude]) |
生成描述性统计信息。 |
Series.diff ([periods]) |
元素的第一个离散差异。 |
Series.factorize ([sort, use_na_sentinel]) |
将对象编码为枚举类型或分类变量。 |
Series.kurt ([axis, skipna, numeric_only]) |
返回请求轴上的无偏峰度。 |
Series.max ([axis, skipna, numeric_only]) |
返回请求轴上的最大值。 |
Series.mean ([axis, skipna, numeric_only]) |
返回请求轴上的均值。 |
Series.median ([axis, skipna, numeric_only]) |
返回请求轴上的中位数。 |
Series.min ([axis, skipna, numeric_only]) |
返回请求轴上的最小值。 |
Series.mode ([dropna]) |
返回 Series 的众数。 |
Series.nlargest ([n, keep]) |
返回最大的 n 个元素。 |
Series.nsmallest ([n, keep]) |
返回最小的 n 个元素。 |
Series.pct_change ([periods, fill_method, ...]) |
当前元素与先前元素之间的分数变化。 |
Series.prod ([axis, skipna, numeric_only, ...]) |
返回请求轴上值的乘积。 |
Series.quantile ([q, interpolation]) |
返回给定分位数处的值。 |
Series.rank ([axis, method, numeric_only, ...]) |
沿轴计算数据的排名(1 到 n)。 |
Series.sem ([axis, skipna, ddof, numeric_only]) |
返回请求轴上均值的无偏标准误差。 |
Series.skew ([axis, skipna, numeric_only]) |
返回请求轴上的无偏偏度。 |
Series.std ([axis, skipna, ddof, numeric_only]) |
返回请求轴上的样��标准差。 |
Series.sum ([axis, skipna, numeric_only, ...]) |
返回请求轴上值的总和。 |
Series.var ([axis, skipna, ddof, numeric_only]) |
返回请求轴上的无偏方差。 |
Series.kurtosis ([axis, skipna, numeric_only]) |
返回请求轴上的无偏峰度。 |
Series.unique () |
返回 Series 对象的唯一值。 |
Series.nunique ([dropna]) |
返回对象中唯一元素的数量。 |
Series.is_unique |
如果对象中的值是唯一的,则返回布尔值。 |
Series.is_monotonic_increasing |
如果对象中的值单调递增,则返回布尔值。 |
Series.is_monotonic_decreasing |
如果对象中的值单调递减,则返回布尔值。 |
Series.value_counts ([normalize, sort, ...]) |
返回包含唯一值计数的 Series。 |
重新索引/选择/标签操作
Series.align (other[, join, axis, level, ...]) |
使用指定的连接方法在它们的轴上对齐两个对象。 |
---|---|
Series.case_when (caselist) |
替换条件为 True 的值。 |
Series.drop ([labels, axis, index, columns, ...]) |
返回删除指定索引标签的 Series。 |
Series.droplevel (level[, axis]) |
返回请求删除的索引/列级别的 Series/DataFrame。 |
Series.drop_duplicates (*[, keep, inplace, ...]) |
返回删除重复值的 Series。 |
Series.duplicated ([keep]) |
指示重复的 Series 值。 |
Series.equals (other) |
测试两个对象是否包含相同的元素。 |
Series.first (offset) |
(已弃用) 根据日期偏移量选择时间序列数据的初始周期。 |
Series.head ([n]) |
返回前 n 行。 |
Series.idxmax ([axis, skipna]) |
返回最大值的行标签。 |
Series.idxmin ([axis, skipna]) |
返回最小值的行标签。 |
Series.isin (values) |
Series 中的元素是否包含在 values 中。 |
Series.last (offset) |
(已弃用) 根据日期偏移量选择时间序列数据的最终周期。 |
Series.reindex ([index, axis, method, copy, ...]) |
将 Series 调整为具有新索引的对象,并可选择填充逻辑。 |
Series.reindex_like (other[, method, copy, ...]) |
返回具有与其他对象匹配索引的对象。 |
Series.rename ([index, axis, copy, inplace, ...]) |
更改 Series 索引标签或名称。 |
Series.rename_axis ([mapper, index, axis, ...]) |
设置索引或列的轴名称。 |
Series.reset_index ([level, drop, name, ...]) |
生成重置索引的新 DataFrame 或 Series。 |
Series.sample ([n, frac, replace, weights, ...]) |
从对象的轴中返回随机样本项。 |
Series.set_axis (labels, *[, axis, copy]) |
为给定轴分配所需的索引。 |
Series.take (indices[, axis]) |
返回沿轴的给定位置索引的元素。 |
Series.tail ([n]) |
返回最后 n 行。 |
Series.truncate ([before, after, axis, copy]) |
在某个索引值之前和之后截断 Series 或 DataFrame。 |
Series.where (cond[, other, inplace, axis, level]) |
替换条件为 False 的值。 |
Series.mask (cond[, other, inplace, axis, level]) |
替换条件为 True 的值。 |
Series.add_prefix (prefix[, axis]) |
使用字符串前缀为标签添加前缀。 |
Series.add_suffix (suffix[, axis]) |
使用字符串后缀为标签添加后缀。 |
Series.filter ([items, like, regex, axis]) |
根据指定的索引标签筛选数据帧的行或列。 |
缺失数据处理
Series.backfill (*[, axis, inplace, limit, ...]) |
(已弃用) 使用下一个有效观察值填充 NA/NaN 值。 |
---|---|
Series.bfill (*[, axis, inplace, limit, ...]) |
使用下一个有效观察值填充 NA/NaN 值。 |
Series.dropna (*[, axis, inplace, how, ...]) |
返回删除缺失值的新 Series。 |
Series.ffill (*[, axis, inplace, limit, ...]) |
通过将最后一个有效观测值传播到下一个有效值来填充 NA/NaN 值。 |
Series.fillna ([value, method, axis, ...]) |
使用指定方法填充 NA/NaN 值。 |
Series.interpolate ([method, axis, limit, ...]) |
使用插值方法填充 NaN 值。 |
Series.isna () |
检测缺失值。 |
Series.isnull () |
Series.isnull 是 Series.isna 的别名。 |
Series.notna () |
检测存在的(非缺失)值。 |
Series.notnull () |
Series.notnull 是 Series.notna 的别名。 |
Series.pad (*[, axis, inplace, limit, downcast]) |
(已弃用)通过将最后一个有效观测值传播到下一个有效值来填充 NA/NaN 值。 |
Series.replace ([to_replace, value, inplace, ...]) |
用 value 替换 to_replace 中的值。 |
重塑、排序
Series.argsort ([axis, kind, order, stable]) |
返回对 Series 值进行排序的整数索引。 |
---|---|
Series.argmin ([axis, skipna]) |
返回 Series 中最小值的整数位置。 |
Series.argmax ([axis, skipna]) |
返回 Series 中最大值的整数位置。 |
Series.reorder_levels (order) |
使用输入顺序重新排列索引级别。 |
Series.sort_values (*[, axis, ascending, ...]) |
按值排序。 |
Series.sort_index (*[, axis, level, ...]) |
按索引标签对 Series 进行排序。 |
Series.swaplevel ([i, j, copy]) |
在MultiIndex 中交换级别 i 和 j。 |
Series.unstack ([level, fill_value, sort]) |
Unstack,也称为 pivot,将具有 MultiIndex 的 Series 转换为 DataFrame。 |
Series.explode ([ignore_index]) |
将类似列表的每个元素转换为一行。 |
Series.searchsorted (value[, side, sorter]) |
查找应插入元素以保持顺序的索引。 |
Series.ravel ([order]) |
(已弃用) 将底层数据扁平化为 ndarray 或 ExtensionArray。 |
Series.repeat (repeats[, axis]) |
重复 Series 的元素。 |
Series.squeeze ([axis]) |
将 1 维轴对象压缩为标量。 |
Series.view ([dtype]) |
(已弃用) 创建 Series 的新视图。 |
合并/比较/连接/合并
Series.compare (other[, align_axis, ...]) |
与另一个 Series 进行比较并显示差异。 |
---|---|
Series.update (other) |
使用传递的 Series 的值就地修改 Series。 |
与时间序列相关
Series.asfreq (freq[, method, how, ...]) |
将时间序列转换为指定的频率。 |
---|---|
Series.asof (where[, subset]) |
返回在 where 之前没有任何 NaN 的最后一行。 |
Series.shift ([periods, freq, axis, ...]) |
通过所需的周期数将索引向前或向后移动,可选择性地使用时间频率。 |
Series.first_valid_index () |
返回第一个非 NA 值的索引,如果找不到非 NA 值,则返回 None。 |
Series.last_valid_index () |
返回最后一个非 NA 值的索引,如果找不到非 NA 值,则返回 None。 |
Series.resample (rule[, axis, closed, label, ...]) |
重新采样时间序列数据。 |
Series.tz_convert (tz[, axis, level, copy]) |
将带有时区信息的轴转换为目标时区。 |
Series.tz_localize (tz[, axis, level, copy, ...]) |
将 Series 或 DataFrame 的 tz-naive 索引本地化到目标时区。 |
Series.at_time (time[, asof, axis]) |
选择一天中特定时间的值(例如,上午 9:30)。 |
Series.between_time (start_time, end_time[, ...]) |
选择一天中特定时间段内的值(例如,上午 9:00-9:30)。 |
访问器
pandas 在各种访问器下提供了特定于数据类型的方法。这些是 Series
内的单独命名空间,仅适用于特定数据类型。
Series.str |
StringMethods 的别名 |
---|---|
Series.cat |
CategoricalAccessor 的别名 |
Series.dt |
CombinedDatetimelikeProperties 的别名 |
Series.sparse |
SparseAccessor 的别名 |
DataFrame.sparse |
SparseFrameAccessor 的别名 |
Index.str |
StringMethods 的别名 |
数据类型 | 访问器 |
--- | --- |
日期时间、时间差、周期 | dt |
字符串 | str |
Categorical | cat |
稀疏 | sparse |
日期时间属性
Series.dt
可用于访问系列的日期时间属性并返回多个属性。这些属性可以像 Series.dt.<property>
这样访问。
日期时间属性
Series.dt.date |
返回带有 python datetime.date 对象的 numpy 数组。 |
---|---|
Series.dt.time |
返回带有时区的 datetime.time 对象的 numpy 数组。 |
Series.dt.timetz |
返回带有时区的 datetime.time 对象的 numpy 数组。 |
Series.dt.year |
日期时间的年份。 |
Series.dt.month |
月份,1 代表一月,12 代表十二月。 |
Series.dt.day |
日期时间的日数。 |
Series.dt.hour |
日期时间的小时数。 |
Series.dt.minute |
日期时间的分钟数。 |
Series.dt.second |
日期时间的秒数。 |
Series.dt.microsecond |
日期时间的微秒数。 |
Series.dt.nanosecond |
日期时间的纳秒数。 |
Series.dt.dayofweek |
星期几,星期一=0,星期日=6。 |
Series.dt.day_of_week |
星期几,星期一=0,星期日=6。 |
Series.dt.weekday |
星期几,星期一=0,星期日=6。 |
Series.dt.dayofyear |
年份中的第几天。 |
Series.dt.day_of_year |
年份中的第几天。 |
Series.dt.days_in_month |
该月的天数。 |
Series.dt.quarter |
日期的季度。 |
Series.dt.is_month_start |
是否为月初的指示器。 |
Series.dt.is_month_end |
是否为月末的指示器。 |
Series.dt.is_quarter_start |
是否为季度第一天的指示器。 |
Series.dt.is_quarter_end |
是否为季度最后一天的指示器。 |
Series.dt.is_year_start |
是否为年初的指示器。 |
Series.dt.is_year_end |
表示日期是否为年末的指示器。 |
Series.dt.is_leap_year |
如果日期属于闰年,则为布尔值指示器。 |
Series.dt.daysinmonth |
一个月中的天数。 |
Series.dt.days_in_month |
一个月中的天数。 |
Series.dt.tz |
返回时区。 |
Series.dt.freq |
返回此 PeriodArray 的频率对象。 |
Series.dt.unit |
时间方法
Series.dt.isocalendar () |
根据 ISO 8601 标准计算年份、周数和日期。 |
---|---|
Series.dt.to_period (*args, **kwargs) |
在特定频率下转换为 PeriodArray/PeriodIndex。 |
Series.dt.to_pydatetime () |
(已弃用)将数据返回为 datetime.datetime 对象数组。 |
Series.dt.tz_localize (*args, **kwargs) |
将时区无关的日期时间数组/索引本地化为时区感知的日期时间数组/索引。 |
Series.dt.tz_convert (*args, **kwargs) |
将时区感知的日期时间数组/索引从一个时区转换为另一个时区。 |
Series.dt.normalize (*args, **kwargs) |
将时间转换为午夜。 |
Series.dt.strftime (*args, **kwargs) |
使用指定的日期格式转换为索引。 |
Series.dt.round (*args, **kwargs) |
对数据执行舍入操作,以指定的频率。 |
Series.dt.floor (*args, **kwargs) |
对数据执行向下取整操作,以指定的频率。 |
Series.dt.ceil (*args, **kwargs) |
对数据执行向上取整操作到指定的频率。 |
Series.dt.month_name (*args, **kwargs) |
返回指定语言环境的月份名称。 |
Series.dt.day_name (*args, **kwargs) |
返回指定语言环境的星期几名称。 |
Series.dt.as_unit (*args, **kwargs) |
期间属性
Series.dt.qyear |
|
---|---|
Series.dt.start_time |
获取周期开始的时间戳。 |
Series.dt.end_time |
获取周期结束的时间戳。 |
时间增量属性
Series.dt.days |
每个元素的天数。 |
---|---|
Series.dt.seconds |
每个元素的秒数(大于等于 0 且小于 1 天)。 |
Series.dt.microseconds |
每个元素的微秒数(大于等于 0 且小于 1 秒)。 |
Series.dt.nanoseconds |
每个元素的纳秒数(大于等于 0 且小于 1 微秒)。 |
Series.dt.components |
返回时间增量的各个组成部分的数据框。 |
Series.dt.unit |
时间增量方法
Series.dt.to_pytimedelta () |
返回一个原生datetime.timedelta 对象数组。 |
---|---|
Series.dt.total_seconds (*args, **kwargs) |
返回每个元素表示的总持续时间(以秒为单位)。 |
| Series.dt.as_unit
(*args, **kwargs) | | ### 字符串处理
Series.str
可用于访问系列的值作为字符串并对其应用多种方法。这些可以像 Series.str.<function/property>
这样访问。
Series.str.capitalize () |
将 Series/Index 中的字符串转换为大写。 |
---|---|
Series.str.casefold () |
将 Series/Index 中的字符串转换为 casefolded。 |
Series.str.cat ([others, sep, na_rep, join]) |
使用给定的分隔符连接 Series/Index 中的字符串。 |
Series.str.center (width[, fillchar]) |
在 Series/Index 中的字符串的左右两侧填充。 |
Series.str.contains (pat[, case, flags, na, ...]) |
测试 Series 或 Index 中的字符串是否包含模式或正则表达式。 |
Series.str.count (pat[, flags]) |
计算 Series/Index 中每个字符串中模式的出现次数。 |
Series.str.decode (encoding[, errors]) |
使用指定的编码解码 Series/Index 中的字符字符串。 |
Series.str.encode (encoding[, errors]) |
使用指定的编码对 Series/Index 中的字符字符串进行编码。 |
Series.str.endswith (pat[, na]) |
测试每个字符串元素的结尾是否与模式匹配。 |
Series.str.extract (pat[, flags, expand]) |
在 DataFrame 中提取正则表达式 pat 中的捕获组作为列。 |
Series.str.extractall (pat[, flags]) |
在 DataFrame 中提取正则表达式 pat 中的捕获组作为列。 |
Series.str.find (sub[, start, end]) |
返回 Series/Index 中每个字符串中的最低索引。 |
Series.str.findall (pat[, flags]) |
在 Series/Index 中查找模式或正则表达式的所有匹配项。 |
Series.str.fullmatch (pat[, case, flags, na]) |
确定每个字符串是否完全匹配正则表达式。 |
Series.str.get (i) |
从指定位置或具有指定键的每个组件中提取元素。 |
Series.str.index (sub[, start, end]) |
返回 Series/Index 中每个字符串中的最低索引。 |
Series.str.join (sep) |
使用传递的分隔符连接 Series/Index 中作为元素包含的列表。 |
Series.str.len () |
计算 Series/Index 中每个元素的长度。 |
Series.str.ljust (width[, fillchar]) |
在 Series/Index 中字符串的右侧填充。 |
Series.str.lower () |
将 Series/Index 中的字符串转换为小写。 |
Series.str.lstrip ([to_strip]) |
移除前导字符。 |
Series.str.match (pat[, case, flags, na]) |
确定每个字符串是否以正则表达式的匹配开头。 |
Series.str.normalize (form) |
返回 Series/Index 中字符串的 Unicode 标准形式。 |
Series.str.pad (width[, side, fillchar]) |
将 Series/Index 中的字符串填充到指定宽度。 |
Series.str.partition ([sep, expand]) |
在第一个分隔符处拆分字符串。 |
Series.str.removeprefix (prefix) |
从对象系列中移除前缀。 |
Series.str.removesuffix (suffix) |
从对象系列中移���后缀。 |
Series.str.repeat (repeats) |
在 Series 或 Index 中复制每个字符串。 |
Series.str.replace (pat, repl[, n, case, ...]) |
替换 Series/Index 中每个出现的模式/正则表达式。 |
Series.str.rfind (sub[, start, end]) |
返回 Series/Index 中每个字符串中的最高索引。 |
Series.str.rindex (sub[, start, end]) |
返回 Series/Index 中每个字符串中的最高索引。 |
Series.str.rjust (width[, fillchar]) |
在 Series/Index 中的字符串左侧填充。 |
Series.str.rpartition ([sep, expand]) |
在字符串中最后一次出现的位置分割字符串。 |
Series.str.rstrip ([to_strip]) |
移除字符串末尾的字符。 |
Series.str.slice ([start, stop, step]) |
从 Series 或 Index 中的每个元素中切片子字符串。 |
Series.str.slice_replace ([start, stop, repl]) |
用另一个值替换字符串的位置切片。 |
Series.str.split ([pat, n, expand, regex]) |
在给定的分隔符周围分割字符串。 |
Series.str.rsplit ([pat, n, expand]) |
在给定的分隔符周围分割字符串。 |
Series.str.startswith (pat[, na]) |
测试每个字符串元素的开头是否与模式匹配。 |
Series.str.strip ([to_strip]) |
移除字符串的前导和尾随字符。 |
Series.str.swapcase () |
将 Series/Index 中的字符串转换为大小写互换。 |
Series.str.title () |
将 Series/Index 中的字符串转换为首字母大写。 |
Series.str.translate (table) |
将字符串中的所有字符通过给定的映射表进行映射。 |
Series.str.upper () |
将 Series/Index 中的字符串转换为大写。 |
Series.str.wrap (width, **kwargs) |
在指定的行宽处将 Series/Index 中的字符串换行。 |
Series.str.zfill (width) |
在 Series/Index 中的字符串前面填充 '0' 字符。 |
Series.str.isalnum () |
检查每个字符串中的所有字符是否为字母数字字符。 |
Series.str.isalpha () |
检查每个字符串中的所有字符是否为字母字符。 |
Series.str.isdigit () |
检查每个字符串中的所有字符是否为数字。 |
Series.str.isspace () |
检查每个字符串中的所有字符是否为空格字符。 |
Series.str.islower () |
检查每个字符串中的所有字符是否为小写。 |
Series.str.isupper () |
检查每个字符串中的所有字符是否为大写。 |
Series.str.istitle () |
检查每个字符串中的所有字符是否为标题大小写。 |
Series.str.isnumeric () |
检查每个字符串中的所有字符是否为数字字符。 |
Series.str.isdecimal () |
检查每个字符串中的所有字符是否为十进制数。 |
| Series.str.get_dummies
([sep]) | 返回 Series 的虚拟/指示变量的 DataFrame。 | ### 分类访问器
分类数据类型特定的方法和属性可在Series.cat
访问器下使用。
Series.cat.categories |
此分类的类别。 |
---|---|
Series.cat.ordered |
类别是否具有有序关系。 |
Series.cat.codes |
返回代码系列以及索引。 |
Series.cat.rename_categories (*args, **kwargs) |
重命名类别。 |
Series.cat.reorder_categories (*args, **kwargs) |
按照新类别指定的顺序重新排序类别。 |
Series.cat.add_categories (*args, **kwargs) |
添加新的分类。 |
Series.cat.remove_categories (*args, **kwargs) |
移除指定的分类。 |
Series.cat.remove_unused_categories (*args, ...) |
移除未使用的分类。 |
Series.cat.set_categories (*args, **kwargs) |
将分类设置为指定的新分类。 |
Series.cat.as_ordered (*args, **kwargs) |
将分类设置为有序。 |
| Series.cat.as_unordered
(*args, **kwargs) | 将分类设置为无序。 ### 稀疏访问器
稀疏数据类型特定的方法和属性可在 Series.sparse
访问器下找到。
Series.sparse.npoints |
非 fill_value 点的数量。 |
---|---|
Series.sparse.density |
非 fill_value 点的百分比,以小数表示。 |
Series.sparse.fill_value |
数据中的 fill_value 元素不会被存储。 |
Series.sparse.sp_values |
包含非 fill_value 值的 ndarray。 |
Series.sparse.from_coo (A[, dense_index]) |
从 scipy.sparse.coo_matrix 创建具有稀疏值的 Series。 |
| Series.sparse.to_coo
([row_levels, ...]) | 从具有 MultiIndex 的 Series 创建 scipy.sparse.coo_matrix。 ### 列表访问器
箭头列表数据类型特定的方法和属性可在 Series.list
访问器下找到。
Series.list.flatten () |
展平列表值。 |
---|---|
Series.list.len () |
返回 Series 中每个列表的长度。 |
| Series.list.__getitem__
(key) | 在 Series 中索引或切片列表。 | ### 结构访问器
Arrow 结构 dtype 特定的方法和属性在 Series.struct
访问器下提供。
Series.struct.dtypes |
返回结构的每个子字段的 dtype 对象。 |
---|---|
Series.struct.field (name_or_index) |
将结构的子字段提取为 Series。 |
| Series.struct.explode
() | 将结构的所有子字段提取为 DataFrame。 | ### 标志
标志指的是 pandas 对象的属性。数据集的属性(如记录日期、访问的 URL 等)应存储在 Series.attrs
中。
| Flags
(obj, *, allows_duplicate_labels) | 适用于 pandas 对象的标志。 | ### 元数据
Series.attrs
是一个用于存储此 Series 的全局元数据的字典。
警告
Series.attrs
被视为实验性的,可能会在没有警告的情况下更改。
| Series.attrs
| 此数据集的全局属性字典。 | ### 日期时间属性
Series.dt
可用于访问系列的日期时间值并返回多个属性。这些可以像 Series.dt.<property>
这样访问。
日期时间属性
Series.dt.date |
返回 python 的 numpy 数组datetime.date 对象。 |
---|---|
Series.dt.time |
返回带有时区的datetime.time 对象的 numpy 数组。 |
Series.dt.timetz |
返回带有时区的datetime.time 对象的 numpy 数组。 |
Series.dt.year |
日期时间的年份。 |
Series.dt.month |
月份,一月为 1,十二月为 12。 |
Series.dt.day |
日期时间的日期。 |
Series.dt.hour |
日期时间的小时。 |
Series.dt.minute |
日期时间的分钟。 |
Series.dt.second |
日期时间的秒。 |
Series.dt.microsecond |
日期时间的微秒。 |
Series.dt.nanosecond |
日期时间的纳秒。 |
Series.dt.dayofweek |
一周中的日期,星期一=0,星期日=6。 |
Series.dt.day_of_week |
一周中的日期,星期一=0,星期日=6。 |
Series.dt.weekday |
一周中的日期,星期一=0,星期日=6。 |
Series.dt.dayofyear |
一年中的日期序数。 |
Series.dt.day_of_year |
一年中的日期序数。 |
Series.dt.days_in_month |
月份的天数。 |
Series.dt.quarter |
日期的季度。 |
Series.dt.is_month_start |
表示日期是否为月初。 |
Series.dt.is_month_end |
表示日期是否为月末。 |
Series.dt.is_quarter_start |
表示日期是否为季度初。 |
Series.dt.is_quarter_end |
表示日期是否为季度末。 |
Series.dt.is_year_start |
表示日期是否为年初。 |
Series.dt.is_year_end |
指示日期是否为年底。 |
Series.dt.is_leap_year |
布尔值指示日期是否属于闰年。 |
Series.dt.daysinmonth |
该月的天数。 |
Series.dt.days_in_month |
该月的天数。 |
Series.dt.tz |
返回时区。 |
Series.dt.freq |
返回此 PeriodArray 的频率对象。 |
Series.dt.unit |
日期时间方法
Series.dt.isocalendar () |
根据 ISO 8601 标准计算年、周和日。 |
---|---|
Series.dt.to_period (*args, **kwargs) |
转换为特定频率的 PeriodArray/PeriodIndex。 |
Series.dt.to_pydatetime () |
(已弃用) 将数据返回为 datetime.datetime 对象的数组。 |
Series.dt.tz_localize (*args, **kwargs) |
将 tz-naive 的日期时间数组/索引本地化为 tz-aware 的日期时间数组/索引。 |
Series.dt.tz_convert (*args, **kwargs) |
将来自一个时区的 tz-aware 的日期时间数组/索引转换为另一个时区。 |
Series.dt.normalize (*args, **kwargs) |
将时间转换为午夜。 |
Series.dt.strftime (*args, **kwargs) |
使用指定的日期格式转换为索引。 |
Series.dt.round (*args, **kwargs) |
对数据执行指定频率的四舍五入操作。 |
Series.dt.floor (*args, **kwargs) |
对数据执行指定频率的向下取整操作。 |
Series.dt.ceil (*args, **kwargs) |
对数据执行向上取整操作到指定的频率。 |
Series.dt.month_name (*args, **kwargs) |
返回指定语言环境下的月份名称。 |
Series.dt.day_name (*args, **kwargs) |
返回指定语言环境下的星期几名称。 |
Series.dt.as_unit (*args, **kwargs) |
时期属性
Series.dt.qyear |
|
---|---|
Series.dt.start_time |
获取周期开始时的时间戳。 |
Series.dt.end_time |
获取周期结束时的时间戳。 |
时间差属性
Series.dt.days |
每个元素的天数。 |
---|---|
Series.dt.seconds |
每个元素的秒数(>= 0 且小于 1 天)。 |
Series.dt.microseconds |
每个元素的微秒数(>= 0 且小于 1 秒)。 |
Series.dt.nanoseconds |
每个元素的纳秒数(>= 0 且小于 1 微秒)。 |
Series.dt.components |
返回时间差的各个组成部分的数据框。 |
Series.dt.unit |
时间差方法
Series.dt.to_pytimedelta () |
返回一个由本地datetime.timedelta 对象组成的数组。 |
---|---|
Series.dt.total_seconds (*args, **kwargs) |
返回每个元素表示的总持续时间(以秒为单位)。 |
Series.dt.as_unit (*args, **kwargs) |
日期时间属性
Series.dt.date |
返回带有 python datetime.date 对象的 numpy 数组。 |
---|---|
Series.dt.time |
返回带有datetime.time 对象的 numpy 数组。 |
Series.dt.timetz |
返回带有时区的datetime.time 对象的 numpy 数组。 |
Series.dt.year |
日期的年份。 |
Series.dt.month |
月份,一月为 1,十二月为 12。 |
Series.dt.day |
日期的日。 |
Series.dt.hour |
日期的小时。 |
Series.dt.minute |
日期的分钟。 |
Series.dt.second |
日期的秒。 |
Series.dt.microsecond |
日期的微秒。 |
Series.dt.nanosecond |
日期的纳秒。 |
Series.dt.dayofweek |
一周中的第几天,星期一为 0,星期日为 6。 |
Series.dt.day_of_week |
一周中的第几天,星期一为 0,星期日为 6。 |
Series.dt.weekday |
一周中的第几天,星期一为 0,星期日为 6。 |
Series.dt.dayofyear |
一年中的第几天。 |
Series.dt.day_of_year |
一年中的第几天。 |
Series.dt.days_in_month |
月份的天数。 |
Series.dt.quarter |
日期的季度。 |
Series.dt.is_month_start |
指示日期是否为一个月的第一天。 |
Series.dt.is_month_end |
指示日期是否为一个月的最后一天。 |
Series.dt.is_quarter_start |
指示日期是否为一个季度的第一天。 |
Series.dt.is_quarter_end |
指示日期是否为一个季度的最后一天。 |
Series.dt.is_year_start |
指示日期是否为一年的第一天。 |
Series.dt.is_year_end |
指示日期是否为一年的最后一天。 |
Series.dt.is_leap_year |
布尔指示器,指示日期是否属于闰年。 |
Series.dt.daysinmonth |
月份中的天数。 |
Series.dt.days_in_month |
月份中的天数。 |
Series.dt.tz |
返回时区。 |
Series.dt.freq |
返回此 PeriodArray 的频率对象。 |
Series.dt.unit |
日期时间方法
Series.dt.isocalendar () |
根据 ISO 8601 标准计算年、周和日。 |
---|---|
Series.dt.to_period (*args, **kwargs) |
在特定频率下转换为 PeriodArray/PeriodIndex。 |
Series.dt.to_pydatetime () |
(已弃用) 将数据返回为 datetime.datetime 对象数组。 |
Series.dt.tz_localize (*args, **kwargs) |
将时区无关的日期时间数组/索引本地化为时区感知的日期时间数组/索引。 |
Series.dt.tz_convert (*args, **kwargs) |
将来自一个时区的时区感知的日期时间数组/索引转换为另一个时区。 |
Series.dt.normalize (*args, **kwargs) |
将时间转换为午夜。 |
Series.dt.strftime (*args, **kwargs) |
使用指定的日期格式转换为索引。 |
Series.dt.round (*args, **kwargs) |
对数据执行四舍五入操作,以指定的频率为准。 |
Series.dt.floor (*args, **kwargs) |
对数据执行向下取整操作,以指定的频率为准。 |
Series.dt.ceil (*args, **kwargs) |
对数据执行向上取整操作,以指定的频率为准。 |
Series.dt.month_name (*args, **kwargs) |
返回指定区域设置的月份名称。 |
Series.dt.day_name (*args, **kwargs) |
返回指定区域设置的星期几名称。 |
Series.dt.as_unit (*args, **kwargs) |
时间周期属性
Series.dt.qyear |
|
---|---|
Series.dt.start_time |
获取周期开始的时间戳。 |
Series.dt.end_time |
获取周期结束的时间戳。 |
时间差属性
Series.dt.days |
每个元素的天数。 |
---|---|
Series.dt.seconds |
每个元素的秒数(>= 0 并且小于 1 天)。 |
Series.dt.microseconds |
每个元素的微秒数(>= 0 并且小于 1 秒)。 |
Series.dt.nanoseconds |
每个元素的纳秒数(>= 0 且小于 1 微秒)。 |
Series.dt.components |
返回时间增量的各个组件的数据框。 |
Series.dt.unit |
时间增量方法
Series.dt.to_pytimedelta () |
返回一个由本地datetime.timedelta 对象组成的数组。 |
---|---|
Series.dt.total_seconds (*args, **kwargs) |
返回每个元素表示的总持续时间(以秒为单位)。 |
Series.dt.as_unit (*args, **kwargs) |
字符串处理
Series.str
可用于访问系列的���作为字符串并应用多种方法。这些可以像Series.str.<function/property>
这样访问。
Series.str.capitalize () |
将系列/索引中的字符串转换为大写。 |
---|---|
Series.str.casefold () |
将系列/索引中的字符串转换为折叠大小写形式。 |
Series.str.cat ([others, sep, na_rep, join]) |
使用给定的分隔符连接系列/索引中的字符串。 |
Series.str.center (width[, fillchar]) |
在系列/索引中的字符串的左侧和右侧填充。 |
Series.str.contains (pat[, case, flags, na, ...]) |
测试模式或正则表达式是否包含在系列或索引的字符串中。 |
Series.str.count (pat[, flags]) |
计算系列/索引中每个字符串中模式的出现次数。 |
Series.str.decode (encoding[, errors]) |
使用指定的编码对系列/索引中的字符字符串进行解码。 |
Series.str.encode (encoding[, errors]) |
使用指定的编码对系列/索引中的字符字符串进行编码。 |
Series.str.endswith (pat[, na]) |
测试每个字符串元素的结尾是否与模式��配。 |
Series.str.extract (pat[, flags, expand]) |
在 DataFrame 中提取正则表达式 pat 中的捕获组作为列。 |
Series.str.extractall (pat[, flags]) |
在 DataFrame 中提取正则表达式 pat 中的捕获组作为列。 |
Series.str.find (sub[, start, end]) |
返回 Series/Index 中每个字符串中的最低索引。 |
Series.str.findall (pat[, flags]) |
在 Series/Index 中查找模式或正则表达式的所有出现。 |
Series.str.fullmatch (pat[, case, flags, na]) |
确定每个字符串是否完全匹配正则表达式。 |
Series.str.get (i) |
从每个组件中提取指定位置或指定键的元素。 |
Series.str.index (sub[, start, end]) |
返回 Series/Index 中每个字符串的最低索引。 |
Series.str.join (sep) |
使用传递的分隔符将 Series/Index 中作为元素包含的列表连接起来。 |
Series.str.len () |
计算 Series/Index 中每个元素的长度。 |
Series.str.ljust (width[, fillchar]) |
在 Series/Index 中字符串的右侧填充。 |
Series.str.lower () |
将 Series/Index 中的字符串转换为小写。 |
Series.str.lstrip ([to_strip]) |
移除前导字符。 |
Series.str.match (pat[, case, flags, na]) |
确定每个字符串是否以正则表达式的匹配开头。 |
Series.str.normalize (form) |
返回 Series/Index 中字符串的 Unicode 标准形式。 |
Series.str.pad |
在 Series/Index 中的字符串中填充到指定宽度。 |
Series.str.partition |
在第一个 sep 出现的位置拆分字符串。 |
Series.str.removeprefix |
从对象系列中删除前缀。 |
Series.str.removesuffix |
从对象系列中删除后缀。 |
Series.str.repeat |
在 Series 或 Index 中复制每个字符串。 |
Series.str.replace |
在 Series/Index 中替换每个模式/正则表达式的每个出现。 |
Series.str.rfind |
返回 Series/Index 中每个字符串中的最高索引。 |
Series.str.rindex |
返回 Series/Index 中每个字符串中的最高索引。 |
Series.str.rjust |
在 Series/Index 中的字符串左侧填充。 |
Series.str.rpartition |
在最后一个 sep 出现的位置拆分字符串。 |
Series.str.rstrip |
移除字符串尾部的字符。 |
Series.str.slice |
从 Series 或 Index 中的每个元素中切割子字符串。 |
Series.str.slice_replace |
用另一个值替换字符串的位置切片。 |
Series.str.split |
在给定的分隔符/定界符周围分割字符串。 |
Series.str.rsplit |
在给定的分隔符/定界符周围分割字符串。 |
Series.str.startswith |
测试每个字符串元素的开头是否与模式匹配。 |
Series.str.strip ([to_strip]) |
移除字符串的开头和结尾字符。 |
Series.str.swapcase () |
将 Series/Index 中的字符串转换为大小写互换。 |
Series.str.title () |
将 Series/Index 中的字符串转换为标题格式。 |
Series.str.translate (table) |
通过给定的映射表映射字符串中的所有字符。 |
Series.str.upper () |
将 Series/Index 中的字符串转换为大写。 |
Series.str.wrap (width, **kwargs) |
在指定的行宽度处将 Series/Index 中的字符串换行。 |
Series.str.zfill (width) |
通过在 Series/Index 中的字符串前面添加 '0' 字符来填充字符串。 |
Series.str.isalnum () |
检查每个字符串中的所有字符是否都是字母数字。 |
Series.str.isalpha () |
检查每个字符串中的所有字符是否都是字母。 |
Series.str.isdigit () |
检查每个字符串中的所有字符是否都是数字。 |
Series.str.isspace () |
检查每个字符串中的所有字符是否都是空白字符。 |
Series.str.islower () |
检查每个字符串中的所有字符是否都是小写。 |
Series.str.isupper () |
检查每个字符串中的所有字符是否都是大写。 |
Series.str.istitle () |
检查每个字符串中的所有字符是否都是标题格式。 |
Series.str.isnumeric () |
检查每个字符串中的所有字符是否都是数字。 |
Series.str.isdecimal () |
检查每个字符串中的所有字符是否都是十进制数。 |
Series.str.get_dummies ([sep]) |
返回 Series 的虚拟/指示变量的 DataFrame。 |
分类访问器
类别特定的方法和属性可在 Series.cat
访问器下找到。
Series.cat.categories |
此分类的类别。 |
---|---|
Series.cat.ordered |
类别是否具有有序关系。 |
Series.cat.codes |
返回代码的 Series 以及索引。 |
Series.cat.rename_categories (*args, **kwargs) |
重命名类别。 |
Series.cat.reorder_categories (*args, **kwargs) |
根据新类别重新排序类别。 |
Series.cat.add_categories (*args, **kwargs) |
添加新类别。 |
Series.cat.remove_categories (*args, **kwargs) |
删除指定的类别。 |
Series.cat.remove_unused_categories (*args, ...) |
删除未使用的类别。 |
Series.cat.set_categories (*args, **kwargs) |
将类别设置为指定的新类别。 |
Series.cat.as_ordered (*args, **kwargs) |
将分类设置为有序。 |
Series.cat.as_unordered (*args, **kwargs) |
将分类设置为无序。 |
稀疏访问器
稀疏特定的方法和属性可在 Series.sparse
访问器下找到。
Series.sparse.npoints |
非 fill_value 点的数量。 |
---|---|
Series.sparse.density |
非 fill_value 点的百分比,以小数表示。 |
Series.sparse.fill_value |
数据中的 fill_value 元素不会被存储。 |
Series.sparse.sp_values |
包含非 fill_value 值的 ndarray。 |
Series.sparse.from_coo (A[, dense_index]) |
从 scipy.sparse.coo_matrix 创建具有稀疏值的 Series。 |
Series.sparse.to_coo ([row_levels, ...]) |
从具有 MultiIndex 的 Series 创建一个 scipy.sparse.coo_matrix。 |
列表访问器
Arrow 列表数据类型的特定方法和属性可在 Series.list
访问器下找到。
Series.list.flatten () |
展平列表值。 |
---|---|
Series.list.len () |
返回 Series 中每个列表的长度。 |
Series.list.__getitem__ (key) |
在 Series 中索引或切片列表。 |
结构访问器
Arrow 结构数据类型的特定方法和属性可在 Series.struct
访问器下找到。
Series.struct.dtypes |
返回结构的每个子字段的 dtype 对象。 |
---|---|
Series.struct.field (name_or_index) |
将结构的子字段提取为 Series。 |
Series.struct.explode () |
将结构的所有子字段提取为 DataFrame。 |
标志
标志指的是 pandas 对象的属性。数据集的属性(如记录日期、访问的 URL 等)应存储在 Series.attrs
中。
Flags (obj, *, allows_duplicate_labels) |
适用于 pandas 对象的标志。 |
---|
元数据
Series.attrs
是一个用于存储此 Series 的全局元数据的字典。
警告
Series.attrs
被视为实验性质,可能会在不经警告的情况下更改。
Series.attrs |
此数据集的全局属性字典。 |
---|
绘图
Series.plot
既是一个可调用方法,也是特定绘图方法的命名空间属性,形式为 Series.plot.<kind>
。
Series.plot ([kind, ax, figsize, ....]) |
Series 绘图访问器和方法 |
---|---|
Series.plot.area ([x, y, stacked]) |
绘制堆叠面积图。 |
Series.plot.bar ([x, y]) |
绘制垂直条形图。 |
Series.plot.barh ([x, y]) |
绘制水平条形图。 |
Series.plot.box ([by]) |
绘制 DataFrame 列的箱线图。 |
Series.plot.density ([bw_method, ind]) |
使用高斯核生成核密度估计图。 |
Series.plot.hist ([by, bins]) |
绘制 DataFrame 列的直方图。 |
Series.plot.kde ([bw_method, ind]) |
使用高斯核生成核密度估计图。 |
Series.plot.line ([x, y]) |
将 Series 或 DataFrame 绘制为折线图。 |
Series.plot.pie (**kwargs) |
生成饼图。 |
Series.hist ([by, ax, grid, xlabelsize, ...]) |
使用 matplotlib 绘制输入序列的直方图。 |
序列化 / IO / 转换
Series.to_pickle (path, *[, compression, ...]) |
将对象序列化(Pickle)到文件。 |
---|---|
Series.to_csv ([path_or_buf, sep, na_rep, ...]) |
将对象写入逗号分隔值(csv)文件。 |
Series.to_dict (*[, into]) |
将 Series 转换为 {标签 -> 值} 字典或类似字典的对象。 |
Series.to_excel (excel_writer, *[, ...]) |
将对象写入 Excel 表格。 |
Series.to_frame ([name]) |
将 Series 转换为 DataFrame。 |
Series.to_xarray () |
从 pandas 对象返回一个 xarray 对象。 |
Series.to_hdf (path_or_buf, *, key[, mode, ...]) |
使用 HDFStore 将包含的数据写入 HDF5 文件。 |
Series.to_sql (name, con, *[, schema, ...]) |
将存储在 DataFrame 中的记录写入 SQL 数据库。 |
Series.to_json ([path_or_buf, orient, ...]) |
将对象转换为 JSON 字符串。 |
Series.to_string ([buf, na_rep, ...]) |
呈现 Series 的字符串表示。 |
Series.to_clipboard (*[, excel, sep]) |
将对象复制到系统剪贴板。 |
Series.to_latex ([buf, columns, header, ...]) |
将对象呈现为 LaTeX 表格、长表格或嵌套表格。 |
Series.to_markdown ([buf, mode, index, ...]) |
以 Markdown 友好的格式打印 Series。 |
pandas.Series
class pandas.Series(data=None, index=None, dtype=None, name=None, copy=None, fastpath=_NoDefault.no_default)
包含轴标签的一维 ndarray(包括时间序列)。
标签不必是唯一的,但必须是可哈希的类型。该对象支持基于整数和标签的索引,并提供了许多涉及索引的操作方法。ndarray 的统计方法已被覆盖以自动排除缺失数据(当前表示为 NaN)。
Series 之间的运算(+、-、/、*、**)会根据它们关联的索引值对齐数据,这些索引值不需要相同长度。结果索引将是这两个索引的排序并集。
参数:
data类似数组,可迭代对象,字典或标量值
包含存储在 Series 中的数据。如果数据是一个字典,则保持参数顺序。
index类似数组或索引(1d)
值必须是可哈希的,并且与数据具有相同的长度。允许非唯一索引值。如果未提供,将默认为 RangeIndex(0、1、2、...、n)。如果数据类似字典并且索引为 None,则使用数据中的键作为索引。如果索引不为 None,则生成的 Series 将根据索引值重新索引。
dtypestr、numpy.dtype 或 ExtensionDtype,可选
输出 Series 的数据类型。如果未指定,则将从数据中推断出。请参阅用户指南获取更多用法。
name可哈希,默认为 None
要赋予 Series 的名称。
copybool,默认为 False
复制输入数据。仅影响 Series 或 1d ndarray 输入。见示例。
注意事项
更多信息,请参考用户指南。
示例
从指定了索引的字典构建 Series
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> ser = pd.Series(data=d, index=['a', 'b', 'c'])
>>> ser
a 1
b 2
c 3
dtype: int64
字典的键与索引值匹配,因此索引值没有影响。
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> ser = pd.Series(data=d, index=['x', 'y', 'z'])
>>> ser
x NaN
y NaN
z NaN
dtype: float64
请注意,索引首先是由字典中的键构建的。之后,Series 会根据给定的索引值重新索引,因此我们会得到全部 NaN 作为结果。
使用 copy=False 从列表构建 Series。
>>> r = [1, 2]
>>> ser = pd.Series(r, copy=False)
>>> ser.iloc[0] = 999
>>> r
[1, 2]
>>> ser
0 999
1 2
dtype: int64
由于输入数据类型,即使 copy=False,Series 也会复制原始数据的副本,因此数据不会改变。
使用 copy=False 从 1d ndarray 构建 Series。
>>> r = np.array([1, 2])
>>> ser = pd.Series(r, copy=False)
>>> ser.iloc[0] = 999
>>> r
array([999, 2])
>>> ser
0 999
1 2
dtype: int64
由于输入数据类型,Series 对原始数据有一个视图,因此数据也会发生变化。
属性
T |
返回转置,按定义为自身。 |
---|---|
array |
支持此 Series 或 Index 的数据的 ExtensionArray。 |
at |
访问行/列标签对的单个值。 |
attrs |
此数据集的全局属性字典。 |
axes |
返回行轴标签列表。 |
dtype |
返回基础数据的 dtype 对象。 |
dtypes |
返回基础数据的 dtype 对象。 |
empty |
指示 Series/DataFrame 是否为空。 |
flags |
获取与此 pandas 对象关联的属性。 |
hasnans |
如果存在任何 NaN,则返回 True。 |
iat |
通过整数位置访问行/列对的单个值。 |
iloc |
(已弃用)纯粹基于整数位置的索引,用于按位置进行选择。 |
index |
Series 的索引(轴标签)。 |
is_monotonic_decreasing |
如果对象中的值是单调递减的,则返回布尔值。 |
is_monotonic_increasing |
如果对象中的值是单调递增的,则返回布尔值。 |
is_unique |
如果对象中的值是唯一的,则返回布尔值。 |
loc |
通过标签或布尔数组访问一组行和列。 |
name |
返回 Series 的名称。 |
nbytes |
返回基础数据中的字节数。 |
ndim |
基础数据的维数,根据定义为 1。 |
shape |
返回基础数据的形状的元组。 |
size |
返回基础数据中的元素数。 |
values |
根据 dtype 返回 Series 作为 ndarray 或类似 ndarray。 |
方法
abs () |
返回每个元素的绝对数值的 Series/DataFrame。 |
---|---|
add (other[, level, fill_value, axis]) |
返回系列和其他的加法,逐元素进行(二进制运算符 add)。 |
add_prefix (prefix[, axis]) |
使用字符串前缀为标签添加前缀。 |
add_suffix (suffix[, axis]) |
使用字符串后缀为标签添加后缀。 |
agg ([func, axis]) |
使用一个或多个操作在指定轴上进行聚合。 |
aggregate ([func, axis]) |
使用一个或多个操作在指定轴上进行聚合。 |
align (other[, join, axis, level, copy, ...]) |
使用指定的连接方法在它们的轴上对齐两个对象。 |
all ([axis, bool_only, skipna]) |
返回是否所有元素都为 True,可能在一个轴上。 |
any (*[, axis, bool_only, skipna]) |
返回是否有任何元素为 True,可能在一个轴上。 |
apply (func[, convert_dtype, args, by_row]) |
对 Series 的值调用函数。 |
argmax ([axis, skipna]) |
返回 Series 中最大值的整数位置。 |
argmin ([axis, skipna]) |
返回 Series 中最小值的整数位置。 |
argsort ([axis, kind, order, stable]) |
返回将 Series 值排序的整数索引。 |
asfreq (freq[, method, how, normalize, ...]) |
将时间序列转换为指定频率。 |
asof (where[, subset]) |
返回在指定位置之前没有任何 NaN 的最后一行。 |
astype (dtype[, copy, errors]) |
将 pandas 对象转换为指定的数据类型 dtype 。 |
at_time (time[, asof, axis]) |
选择特定时间的值(例如,上午 9:30)。 |
autocorr ([lag]) |
计算滞后 N 的自相关性。 |
backfill (*[, axis, inplace, limit, downcast]) |
(已弃用) 使用下一个有效观察值填充 NA/NaN 值以填补间隙。 |
between (left, right[, inclusive]) |
返回布尔 Series,等效于 left <= series <= right。 |
between_time (start_time, end_time[, ...]) |
选择一天中特定时间段之间的值(例如,上午 9:00-9:30)。 |
bfill (*[, axis, inplace, limit, limit_area, ...]) |
使用下一个有效观测值填充 NA/NaN 值。 |
bool () |
(已弃用)返回单个元素 Series 或 DataFrame 的布尔值。 |
case_when (caselist) |
替换条件为 True 的值。 |
clip ([lower, upper, axis, inplace]) |
在输入阈值处修剪值。 |
combine (other, func[, fill_value]) |
根据 func 将 Series 与 Series 或标量组合。 |
combine_first (other) |
使用 'other' 中相同位置的值更新空元素。 |
compare (other[, align_axis, keep_shape, ...]) |
与另一个 Series 进行比较并显示差异。 |
convert_dtypes ([infer_objects, ...]) |
使用支持 pd.NA 的 dtypes 将列转换为最佳可能的 dtypes。 |
copy ([deep]) |
复制此对象的索引和数据。 |
corr (other[, method, min_periods]) |
计算与其他 Series 的相关性,不包括缺失值。 |
count () |
返回 Series 中非 NA/null 观测值的数量。 |
cov (other[, min_periods, ddof]) |
计算与 Series 的协方差,不包括缺失值。 |
cummax ([axis, skipna]) |
返回 DataFrame 或 Series 轴上的累积最大值。 |
cummin ([axis, skipna]) |
返回 DataFrame 或 Series 轴上的累积最小值。 |
cumprod ([axis, skipna]) |
返回 DataFrame 或 Series 轴上的累积乘积。 |
cumsum ([axis, skipna]) |
返回 DataFrame 或 Series 轴上的累积和。 |
describe ([percentiles, include, exclude]) |
生成描述性统计信息。 |
diff ([periods]) |
元素的第一个离散差异。 |
div (other[, level, fill_value, axis]) |
返回系列和其他元素的浮点除法,逐元素进行(二元运算符 truediv)。 |
divide (other[, level, fill_value, axis]) |
返回系列和其他元素的浮点除法,逐元素进行(二元运算符 truediv)。 |
divmod (other[, level, fill_value, axis]) |
返回系列和其他元素的整数除法和模数,逐元素进行(二元运算符 divmod)。 |
dot (other) |
计算 Series 和其他列之间的点积。 |
drop ([labels, axis, index, columns, level, ...]) |
返回删除指定索引标签的 Series。 |
drop_duplicates (*[, keep, inplace, ignore_index]) |
返回删除重复值的 Series。 |
droplevel (level[, axis]) |
返回删除请求的索引/列级别的 Series/DataFrame。 |
dropna (*[, axis, inplace, how, ignore_index]) |
返回删除缺失值的新 Series。 |
duplicated ([keep]) |
表示 Series 值是否重复。 |
eq (other[, level, fill_value, axis]) |
返回系列���其他元素的相等,逐元素进行(二元运算符 eq)。 |
equals (other) |
测试两个对象是否包含相同的元素。 |
ewm ([com, span, halflife, alpha, ...]) |
提供指数加权(EW)计算。 |
expanding ([min_periods, axis, method]) |
提供扩展窗口计算。 |
explode ([ignore_index]) |
将类似列表的每个元素转换为一行。 |
factorize ([sort, use_na_sentinel]) |
将对象编码为枚举类型或分类变量。 |
ffill (*[, axis, inplace, limit, limit_area, ...]) |
通过将最后一个有效观察传播到下一个有效值,填充 NA/NaN 值。 |
fillna ([value, method, axis, inplace, ...]) |
使用指定方法填充 NA/NaN 值。 |
filter ([items, like, regex, axis]) |
根据指定的索引标签,对数据帧行或列进行子集选择。 |
first (offset) |
(已弃用)根据日期偏移量选择时间序列数据的初始周期。 |
first_valid_index () |
返回第一个非 NA 值的索引,如果没有找到非 NA 值,则返回 None。 |
floordiv (other[, level, fill_value, axis]) |
返回序列和其他的整数除法,逐元素(二进制运算符 floordiv)。 |
ge (other[, level, fill_value, axis]) |
返回序列和其他的大于或等于,逐元素(二进制运算符 ge)。 |
get (key[, default]) |
获取给定键的对象中的项(例如:DataFrame 列)。 |
groupby ([by, axis, level, as_index, sort, ...]) |
使用映射器或列的 Series 进行分组。 |
gt (other[, level, fill_value, axis]) |
返回序列和其他的大于,逐元素(二进制运算符 gt)。 |
head ([n]) |
返回前 n 行。 |
hist ([by, ax, grid, xlabelsize, xrot, ...]) |
使用 matplotlib 绘制输入系列的直方图。 |
idxmax ([axis, skipna]) |
返回最大值的行标签。 |
idxmin ([axis, skipna]) |
返回最小值的行标签。 |
infer_objects ([copy]) |
尝试推断对象列的更好的数据类型。 |
info ([verbose, buf, max_cols, memory_usage, ...]) |
打印 Series 的简洁摘要。 |
interpolate ([method, axis, limit, inplace, ...]) |
使用插值方法填充 NaN 值。 |
isin (values) |
Series 中的元素是否包含在 values 中。 |
isna () |
检测缺失值。 |
isnull () |
Series.isnull 是 Series.isna 的别名。 |
item () |
将底层数据的第一个元素作为 Python 标量返回。 |
items () |
惰性地遍历 (index, value) 元组。 |
keys () |
返回索引的别名。 |
kurt ([axis, skipna, numeric_only]) |
返回请求轴上的无偏峰度。 |
kurtosis ([axis, skipna, numeric_only]) |
返回请求轴上的无偏峰度。 |
last (offset) |
(已弃用) 根据日期偏移选择时间序列数据的最终周期。 |
last_valid_index () |
返回最后一个非 NA 值的索引,如果找不到非 NA 值,则返回 None。 |
le (other[, level, fill_value, axis]) |
返回 series 和 other 的小于或等于值,逐元素进行比较(二元运算符 le)。 |
lt (other[, level, fill_value, axis]) |
返回 series 和 other 的小于值,逐元素进行比较(二元运算符 lt)。 |
map (arg[, na_action]) |
根据输入映射或函数映射 Series 的值。 |
mask (cond[, other, inplace, axis, level]) |
替换条件为 True 的值。 |
max ([axis, skipna, numeric_only]) |
返回请求轴上的值的最大值。 |
mean ([axis, skipna, numeric_only]) |
返回请求轴上的值的平均值。 |
median ([axis, skipna, numeric_only]) |
返回请求轴上的值的中位数。 |
memory_usage ([index, deep]) |
返回 Series 的内存使用情况。 |
min ([axis, skipna, numeric_only]) |
返回请求轴上的值的最小值。 |
mod (other[, level, fill_value, axis]) |
返回系列和其他的模数,逐元素计算(二元运算符 mod)。 |
mode ([dropna]) |
返回 Series 的众数(mode)。 |
mul (other[, level, fill_value, axis]) |
返回系列和其他的乘法,逐元素计算(二元运算符 mul)。 |
multiply (other[, level, fill_value, axis]) |
返回系列和其他的乘法,逐元素计算(二元运算符 mul)。 |
ne (other[, level, fill_value, axis]) |
返回系列和其他的不等于,逐元素计算���二元运算符 ne)。 |
nlargest ([n, keep]) |
返回最大的 n 个元素。 |
notna () |
检测存在的(非缺失)值。 |
notnull () |
Series.notnull 是 Series.notna 的别名。 |
nsmallest ([n, keep]) |
返回最小的 n 个元素。 |
nunique ([dropna]) |
返回对象中唯一元素的数量。 |
pad (*[, axis, inplace, limit, downcast]) |
(已弃用)通过将最后一个有效观察结果传播到下一个有效观察结果来填充 NA/NaN 值。 |
pct_change ([periods, fill_method, limit, freq]) |
当前元素与先前元素之间的分数变化。 |
pipe (func, *args, **kwargs) |
应用可链式调用的函数,期望 Series 或 DataFrame。 |
pop (item) |
返回项目并从系列中删除。 |
pow (other[, level, fill_value, axis]) |
返回系列和其他的指数幂,逐元素计算(二元运算符 pow)。 |
prod ([axis, skipna, numeric_only, min_count]) |
返回沿请求轴的值的乘积。 |
product ([axis, skipna, numeric_only, min_count]) |
返回沿请求轴的值的乘积。 |
quantile ([q, interpolation]) |
返回给定分位数处的值。 |
radd (other[, level, fill_value, axis]) |
返回系列和其他元素的加法,逐元素进行(二进制运算符 radd)。 |
rank ([axis, method, numeric_only, ...]) |
沿轴计算数值数据排名(1 到 n)。 |
ravel ([order]) |
(已弃用) 将底层数据展平为 ndarray 或 ExtensionArray。 |
rdiv (other[, level, fill_value, axis]) |
返回系列和其他元素的浮点除法,逐元素进行(二进制运算符 rtruediv)。 |
rdivmod (other[, level, fill_value, axis]) |
返回系列和其他元素的整数除法和取模,逐元素进行(二进制运算符 rdivmod)。 |
reindex ([index, axis, method, copy, level, ...]) |
将 Series 调整为具有可选填充逻辑的新索引。 |
reindex_like (other[, method, copy, limit, ...]) |
返回具有与其他对象匹配索引的对象。 |
rename ([index, axis, copy, inplace, level, ...]) |
更改 Series 索引标签或名称。 |
rename_axis ([mapper, index, axis, copy, inplace]) |
为索引或列设置轴的名称。 |
reorder_levels (order) |
使用输入顺序重新排列索引级别。 |
repeat (repeats[, axis]) |
重复 Series 的元素。 |
replace ([to_replace, value, inplace, limit, ...]) |
用给定值替换 to_replace 中的值。 |
resample (rule[, axis, closed, label, ...]) |
对时间序列数据进行重新采样。 |
reset_index ([level, drop, name, inplace, ...]) |
生成具有重置索引的新 DataFrame 或 Series。 |
rfloordiv (other[, level, fill_value, axis]) |
返回系列和其他元素的整数除法,逐元素进行(二进制运算符 rfloordiv)。 |
rmod (other[, level, fill_value, axis]) |
返回系列和其他元素的取模,逐元素进行(二进制运算符 rmod)。 |
rmul (other[, level, fill_value, axis]) |
返回系列和其他元素的乘积,逐元素计算(二进制运算符 rmul)。 |
rolling (window[, min_periods, center, ...]) |
提供滚动窗口计算。 |
round ([decimals]) |
将系列中的每个值四舍五入到给定的小数位数。 |
rpow (other[, level, fill_value, axis]) |
返回序列和其他元素的指数幂,逐元素计算(二进制运算符 rpow)。 |
rsub (other[, level, fill_value, axis]) |
返回系列和其他元素的差异,逐元素计算(二进制运算符 rsub)。 |
rtruediv (other[, level, fill_value, axis]) |
返回系列和其他元素的浮点除法,逐元素计算(二进制运算符 rtruediv)。 |
sample ([n, frac, replace, weights, ...]) |
从对象的轴中返回随机样本项目。 |
searchsorted (value[, side, sorter]) |
找到应插入元素以维护顺序的索引。 |
sem ([axis, skipna, ddof, numeric_only]) |
返回请求轴上的无偏均值标准误差。 |
set_axis (labels, *[, axis, copy]) |
将所需的索引分配给给定的轴。 |
set_flags (*[, copy, allows_duplicate_labels]) |
返回带有更新标志的新对象。 |
shift ([periods, freq, axis, fill_value, suffix]) |
将索引按所需的周期数移动,并可选择性地指定时间频率。 |
skew ([axis, skipna, numeric_only]) |
返回请求轴上的无偏倾斜度。 |
sort_index (*[, axis, level, ascending, ...]) |
按索引标签对系列进行排序。 |
sort_values (*[, axis, ascending, inplace, ...]) |
按值排序。 |
squeeze ([axis]) |
将 1 维轴对象压缩为标量。 |
std ([axis, skipna, ddof, numeric_only]) |
返回请求轴上的样本标准差。 |
sub (other[, level, fill_value, axis]) |
返回系列和其他元素的减法,逐元素进行(二进制运算符 sub)。 |
subtract (other[,��level, fill_value, axis]) |
返回系列和其他元素的减法,逐元素进行(二进制运算符 sub)。 |
sum ([axis, skipna, numeric_only, min_count]) |
返回请求轴上值的总和。 |
swapaxes (axis1, axis2[, copy]) |
(已弃用)交换轴并适当交换值轴。 |
swaplevel ([i, j, copy]) |
在 MultiIndex 中交换级别 i 和 j。 |
tail ([n]) |
返回最后 n 行。 |
take (indices[, axis]) |
返回沿轴的给定 位置 索引的元素。 |
to_clipboard (*[, excel, sep]) |
将对象复制到系统剪贴板。 |
to_csv ([path_or_buf, sep, na_rep, ...]) |
将对象写入逗号分隔值(csv)文件。 |
to_dict (*[, into]) |
将 Series 转换为 {label -> value} 字典或类似字典的对象。 |
to_excel (excel_writer, *[, sheet_name, ...]) |
将对象写入 Excel 表。 |
to_frame ([name]) |
将 Series 转换为 DataFrame。 |
to_hdf (path_or_buf, *, key[, mode, ...]) |
使用 HDFStore 将包含的数据写入 HDF5 文件。 |
to_json ([path_or_buf, orient, date_format, ...]) |
将对象转换为 JSON 字符串。 |
to_latex ([buf, columns, header, index, ...]) |
将对象呈现为 LaTeX 表格、长表格或嵌套表格。 |
to_list () |
返回值的列表。 |
to_markdown ([buf, mode, index, storage_options]) |
以 Markdown 友好的格式打印 Series。 |
to_numpy ([dtype, copy, na_value]) |
表示此 Series 或索引中的值的 NumPy ndarray。 |
to_period ([freq, copy]) |
将 Series 从 DatetimeIndex 转换为 PeriodIndex。 |
to_pickle (path, *[, compression, protocol, ...]) |
将对象保存为 pickle(序列化)文件。 |
to_sql (name, con, *[, schema, if_exists, ...]) |
将存储在 DataFrame 中的记录写入 SQL 数据库。 |
to_string ([buf, na_rep, float_format, ...]) |
渲染 Series 的字符串表示形式。 |
to_timestamp ([freq, how, copy]) |
转换为 Timestamps 的 DatetimeIndex,位于周期的 开始 处。 |
to_xarray () |
从 pandas 对象返回一个 xarray 对象。 |
tolist () |
返回值的列表形式。 |
transform (func[, axis]) |
对自身调用 func ,产生一个与自身轴形状相同的 Series。 |
transpose (*args, **kwargs) |
返回转置,其定义为自身。 |
truediv (other[, level, fill_value, axis]) |
返回系列和其他的浮点除法,逐元素进行(二元运算符 truediv)。 |
truncate ([before, after, axis, copy]) |
在某个索引值之前和之后截断 Series 或 DataFrame。 |
tz_convert (tz[, axis, level, copy]) |
将带有时区信息的轴转换为目标时区。 |
tz_localize (tz[, axis, level, copy, ...]) |
将 Series 或 DataFrame 的时区无关索引本地化为目标时区。 |
unique () |
返回 Series 对象的唯一值。 |
unstack ([level, fill_value, sort]) |
将具有 MultiIndex 的 Series 进行解压缩,也称为透视,以生成 DataFrame。 |
update (other) |
使用传入的 Series 的值就地修改 Series。 |
value_counts ([normalize, sort, ascending, ...]) |
返回包含唯一值计数的 Series。 |
var ([axis, skipna, ddof, numeric_only]) |
返回所请求轴上的无偏方差。 |
view ([dtype]) |
(已弃用) 创建 Series 的新视图。 |
where (cond[, other, inplace, axis, level]) |
替换条件为假的值。 |
xs (key[, axis, level, drop_level]) |
从 Series/DataFrame 返回横截面。 |
pandas.Series.index
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.index.html
Series.index
Series 的索引(轴标签)。
一个 Series 的索引被用来标记和识别底层数据的每个元素。索引可以被看作是一个不可变的有序集合(技术上是一个多重集,因为它可能包含重复的标签),并且被用于在 pandas 中索引和对齐数据。
返回:
索引
Series 的索引标签。
另请参阅
Series.reindex
将 Series 调整到新的索引。
Index
pandas 的基础索引类型。
注意
关于 pandas 索引的更多信息,请参阅索引用户指南。
示例
要创建一个带有自定义索引并查看索引标签的 Series:
>>> cities = ['Kolkata', 'Chicago', 'Toronto', 'Lisbon']
>>> populations = [14.85, 2.71, 2.93, 0.51]
>>> city_series = pd.Series(populations, index=cities)
>>> city_series.index
Index(['Kolkata', 'Chicago', 'Toronto', 'Lisbon'], dtype='object')
要更改现有 Series 的索引标签:
>>> city_series.index = ['KOL', 'CHI', 'TOR', 'LIS']
>>> city_series.index
Index(['KOL', 'CHI', 'TOR', 'LIS'], dtype='object')
pandas.Series.array
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.array.html
property Series.array
支持此 Series 或 Index 的数据的 ExtensionArray。
返回:
ExtensionArray
存储的值的 ExtensionArray。对于扩展类型,这是实际的数组。对于 NumPy 原生类型,这是一个薄的(无需复制)包装器,包围着 numpy.ndarray
.
.array
与 .values
不同,可能需要将数据转换为不同的形式。
另请参阅
Index.to_numpy
一个始终返回 NumPy 数组的类似方法。
Series.to_numpy
一个始终返回 NumPy 数组的类似方法。
注意
此表列出了 pandas 中每个扩展 dtype 的不同数组类型。
dtype | 数组类型 |
---|---|
category | Categorical |
period | PeriodArray |
interval | IntervalArray |
IntegerNA | IntegerArray |
string | StringArray |
boolean | BooleanArray |
datetime64[ns, tz] | DatetimeArray |
对于任何第三方扩展类型,数组类型将是一个 ExtensionArray。
对于所有剩余的 dtypes,.array
将是一个 arrays.NumpyExtensionArray
,包装了实际存储的 ndarray。如果您绝对需要一个 NumPy 数组(可能需要复制/强制转换数据),那么请使用 Series.to_numpy()
。
示例
对于常规的 NumPy 类型,如 int 和 float,将返回一个 NumpyExtensionArray。
>>> pd.Series([1, 2, 3]).array
<NumpyExtensionArray>
[1, 2, 3]
Length: 3, dtype: int64
对于类别型等扩展类型,将返回实际的 ExtensionArray。
>>> ser = pd.Series(pd.Categorical(['a', 'b', 'a']))
>>> ser.array
['a', 'b', 'a']
Categories (2, object): ['a', 'b']
pandas.Series.values
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.values.html
property Series.values
根据 dtype 返回 Series 作为 ndarray 或类似 ndarray。
警告
我们建议使用Series.array
或Series.to_numpy()
,取决于您是否需要对基础数据的引用或 NumPy 数组。
返回:
numpy.ndarray 或类似 ndarray
另请参见
Series.array
对基础数据的引用。
Series.to_numpy
代表基础数据的 NumPy 数组。
示例
>>> pd.Series([1, 2, 3]).values
array([1, 2, 3])
>>> pd.Series(list('aabc')).values
array(['a', 'a', 'b', 'c'], dtype=object)
>>> pd.Series(list('aabc')).astype('category').values
['a', 'a', 'b', 'c']
Categories (3, object): ['a', 'b', 'c']
时区感知的日期时间数据被转换为 UTC:
>>> pd.Series(pd.date_range('20130101', periods=3,
... tz='US/Eastern')).values
array(['2013-01-01T05:00:00.000000000',
'2013-01-02T05:00:00.000000000',
'2013-01-03T05:00:00.000000000'], dtype='datetime64[ns]')
pandas.Series.dtype
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.dtype.html
property Series.dtype
返回底层数据的 dtype 对象。
示例
>>> s = pd.Series([1, 2, 3])
>>> s.dtype
dtype('int64')
pandas.Series.shape
pandas.pydata.org/docs/reference/api/pandas.Series.shape.html
property Series.shape
返回基础数据的形状的元组。
示例
>>> s = pd.Series([1, 2, 3])
>>> s.shape
(3,)
pandas.Series.nbytes
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.nbytes.html
property Series.nbytes
返回基础数据中的字节数。
示例
对于系列:
>>> s = pd.Series(['Ant', 'Bear', 'Cow'])
>>> s
0 Ant
1 Bear
2 Cow
dtype: object
>>> s.nbytes
24
对于索引:
>>> idx = pd.Index([1, 2, 3])
>>> idx
Index([1, 2, 3], dtype='int64')
>>> idx.nbytes
24
pandas.Series.ndim
pandas.pydata.org/docs/reference/api/pandas.Series.ndim.html
property Series.ndim
底层数据的维度数量,根据定义为 1。
示例
>>> s = pd.Series(['Ant', 'Bear', 'Cow'])
>>> s
0 Ant
1 Bear
2 Cow
dtype: object
>>> s.ndim
1
对于索引:
>>> idx = pd.Index([1, 2, 3])
>>> idx
Index([1, 2, 3], dtype='int64')
>>> idx.ndim
1
pandas.Series.size
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.size.html
property Series.size
返回底层数据中元素的数量。
示例
对于 Series:
>>> s = pd.Series(['Ant', 'Bear', 'Cow'])
>>> s
0 Ant
1 Bear
2 Cow
dtype: object
>>> s.size
3
对于 Index:
>>> idx = pd.Index([1, 2, 3])
>>> idx
Index([1, 2, 3], dtype='int64')
>>> idx.size
3
pandas.Series.T
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.T.html
property Series.T
返回转置,根据定义是自身。
例子
对于 Series:
>>> s = pd.Series(['Ant', 'Bear', 'Cow'])
>>> s
0 Ant
1 Bear
2 Cow
dtype: object
>>> s.T
0 Ant
1 Bear
2 Cow
dtype: object
对于索引:
>>> idx = pd.Index([1, 2, 3])
>>> idx.T
Index([1, 2, 3], dtype='int64')
pandas.Series.memory_usage
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.memory_usage.html
Series.memory_usage(index=True, deep=False)
返回 Series 的内存使用量。
内存使用量可以选择包括索引和对象数据类型元素的贡献。
参数:
indexbool,默认为 True
指定是否包括 Series 索引的内存使用量。
deepbool,默认为 False
如果为 True,则通过查询对象数据类型以获取系统级内存消耗来深入检查数据,并将其包含在返回值中。
返回:
int
消耗的内存字节数。
另请参阅
数组元素消耗的总字节数。
DataFrame.memory_usage
DataFrame 消耗的字节。
示例
>>> s = pd.Series(range(3))
>>> s.memory_usage()
152
不包括索引会给出数据的其余部分的大小,这部分大小必然更小:
>>> s.memory_usage(index=False)
24
默认情况下忽略对象值的内存占用:
>>> s = pd.Series(["a", "b"])
>>> s.values
array(['a', 'b'], dtype=object)
>>> s.memory_usage()
144
>>> s.memory_usage(deep=True)
244
pandas.Series.hasnans
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.hasnans.html
property Series.hasnans
如果有任何 NaN,则返回 True。
启用各种性能加速。
返回:
bool
示例
>>> s = pd.Series([1, 2, 3, None])
>>> s
0 1.0
1 2.0
2 3.0
3 NaN
dtype: float64
>>> s.hasnans
True
pandas.Series.empty
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.empty.html
property Series.empty
指示 Series/DataFrame 是否为空。
如果 Series/DataFrame 完全为空(没有任何项),意味着任一轴的长度为 0。
返回:
布尔值
如果 Series/DataFrame 为空,则返回 True,否则返回 False。
另请参阅
返回不含空值的 Series。
返回在给定轴上省略标签的 DataFrame,其中(所有或任何)数据缺失。
笔记
如果 Series/DataFrame 仅包含 NaN,则仍然不被视为空。请参阅下面的示例。
示例
实际空 DataFrame 的示例。请注意索引为空:
>>> df_empty = pd.DataFrame({'A' : []})
>>> df_empty
Empty DataFrame
Columns: [A]
Index: []
>>> df_empty.empty
True
如果我们的 DataFrame 中只有 NaN,它不被视为空!我们需要删除 NaN 使 DataFrame 为空:
>>> df = pd.DataFrame({'A' : [np.nan]})
>>> df
A
0 NaN
>>> df.empty
False
>>> df.dropna().empty
True
>>> ser_empty = pd.Series({'A' : []})
>>> ser_empty
A []
dtype: object
>>> ser_empty.empty
False
>>> ser_empty = pd.Series()
>>> ser_empty.empty
True
pandas.Series.dtypes
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.dtypes.html
property Series.dtypes
返回基础数据的 dtype 对象。
示例
>>> s = pd.Series([1, 2, 3])
>>> s.dtypes
dtype('int64')
pandas.Series.name
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.name.html
property Series.name
返回 Series 的名称。
如果 Series 用于构成 DataFrame,则 Series 的名称变为其索引或列名。在使用解释器显示 Series 时也会使用它。
返回:
标签(可散列对象)
Series 的名称,如果是 DataFrame 的一部分,则也是列名。
另请参阅
Series.rename
给定标量输入时设置 Series 名称。
Index.name
对应的 Index 属性。
示例
在调用构造函数时可以最初设置 Series 名称。
>>> s = pd.Series([1, 2, 3], dtype=np.int64, name='Numbers')
>>> s
0 1
1 2
2 3
Name: Numbers, dtype: int64
>>> s.name = "Integers"
>>> s
0 1
1 2
2 3
Name: Integers, dtype: int64
DataFrame 中 Series 的名称是其列名。
>>> df = pd.DataFrame([[1, 2], [3, 4], [5, 6]],
... columns=["Odd Numbers", "Even Numbers"])
>>> df
Odd Numbers Even Numbers
0 1 2
1 3 4
2 5 6
>>> df["Even Numbers"].name
'Even Numbers'
pandas.Series.flags
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.flags.html
property Series.flags
获取与此 pandas 对象关联的属性。
可用的标志有
Flags.allows_duplicate_labels
参见
Flags
适用于 pandas 对象的标志。
DataFrame.attrs
适用于此数据集的全局元数据。
注意
“标志”与“元数据”不同。标志反映了 pandas 对象(Series 或 DataFrame)的属性。元数据指的是数据集的属性,应存储在DataFrame.attrs
中。
示例
>>> df = pd.DataFrame({"A": [1, 2]})
>>> df.flags
<Flags(allows_duplicate_labels=True)>
可以使用.
来获取或设置标志。
>>> df.flags.allows_duplicate_labels
True
>>> df.flags.allows_duplicate_labels = False
或通过使用键进行切片
>>> df.flags["allows_duplicate_labels"]
False
>>> df.flags["allows_duplicate_labels"] = True
pandas.Series.set_flags
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.set_flags.html
Series.set_flags(*, copy=False, allows_duplicate_labels=None)
返回一个更新了标志的新对象。
参数:
copybool,默认为 False
指定是否应复制对象。
注意
在 pandas 3.0 中,copy 关键字的行为将发生变化。 写时复制 将默认启用,这意味着所有带有 copy 关键字的方法将使用惰性复制机制来推迟复制并忽略 copy 关键字。 copy 关键字将在未来版本的 pandas 中删除。
通过启用写时复制 pd.options.mode.copy_on_write = True
,您已经可以获得未来的行为和改进。
allows_duplicate_labelsbool,可选
返回对象是否允许重复标签。
返回:
Series 或 DataFrame
调用者的相同类型。
另请参阅
DataFrame.attrs
适用于此数据集的全局元数据。
DataFrame.flags
适用于此对象的全局标志。
注意事项
此方法返回一个新对象,该对象是输入数据的视图。 修改输入或输出值将反映在另一个值中。
该方法旨在用于方法链中使用。
“Flags”与“元数据”不同。 标志反映了 pandas 对象(Series 或 DataFrame)的属性。 元数据指数据集的属性,应存储在 DataFrame.attrs
中。
示例
>>> df = pd.DataFrame({"A": [1, 2]})
>>> df.flags.allows_duplicate_labels
True
>>> df2 = df.set_flags(allows_duplicate_labels=False)
>>> df2.flags.allows_duplicate_labels
False
pandas.Series.astype
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.astype.html
Series.astype(dtype, copy=None, errors='raise')
将 pandas 对象转换为指定的数据类型dtype
。
参数:
dtypestr,数据类型,Series 或列名 -> 数据类型的映射
使用字符串、numpy.dtype、pandas.ExtensionDtype 或 Python 类型将整个 pandas 对象转换为相同类型。或者,使用映射,例如{col: dtype, …},其中 col 是列标签,dtype 是 numpy.dtype 或 Python 类型,将数据框的一个或多个列转换为特定类型。
copybool,默认为 True
当copy=True
时返回一个副本(设置copy=False
时要非常小心,因为值的更改可能传播到其他 pandas 对象)。
注意
copy
关键字在 pandas 3.0 中的行为将发生变化。写时复制将默认启用,这意味着所有带有copy
关键字的方法将使用延迟复制机制来推迟复制并忽略copy
关键字。copy
关键字将在未来版本的 pandas 中被移除。
通过启用写时复制pd.options.mode.copy_on_write = True
,您已经可以获得未来的行为和改进。
errors,默认为‘raise’
控制对提供的数据类型的无效数据引发异常。
-
raise
:允许引发异常 -
ignore
:忽略异常。出错时返回原始对象。
返回:
与调用者相同的类型
另请参阅
to_datetime
将参数转换为日期时间。
to_timedelta
将参数转换为时间间隔。
to_numeric
将参数转换为数值类型。
将 numpy 数组转换为指定类型。
注意
从版本 2.0.0 开始更改:使用astype
从时区无关的数据类型转换为时区感知的数据类型将引发异常。请改用Series.dt.tz_localize()
。
示例
创建一个数据框:
>>> d = {'col1': [1, 2], 'col2': [3, 4]}
>>> df = pd.DataFrame(data=d)
>>> df.dtypes
col1 int64
col2 int64
dtype: object
将所有列转换为 int32:
>>> df.astype('int32').dtypes
col1 int32
col2 int32
dtype: object
使用字典将 col1 转换为 int32:
>>> df.astype({'col1': 'int32'}).dtypes
col1 int32
col2 int64
dtype: object
创建一个系列:
>>> ser = pd.Series([1, 2], dtype='int32')
>>> ser
0 1
1 2
dtype: int32
>>> ser.astype('int64')
0 1
1 2
dtype: int64
转换为分类类型:
>>> ser.astype('category')
0 1
1 2
dtype: category
Categories (2, int32): [1, 2]
将转换为具有自定义排序的有序分类类型:
>>> from pandas.api.types import CategoricalDtype
>>> cat_dtype = CategoricalDtype(
... categories=[2, 1], ordered=True)
>>> ser.astype(cat_dtype)
0 1
1 2
dtype: category
Categories (2, int64): [2 < 1]
创建一个日期系列:
>>> ser_date = pd.Series(pd.date_range('20200101', periods=3))
>>> ser_date
0 2020-01-01
1 2020-01-02
2 2020-01-03
dtype: datetime64[ns]
pandas.Series.convert_dtypes
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.convert_dtypes.html
Series.convert_dtypes(infer_objects=True, convert_string=True, convert_integer=True, convert_boolean=True, convert_floating=True, dtype_backend='numpy_nullable')
使用支持pd.NA
的数据类型将列转换为最佳可能的数据类型。
参数:
infer_objectsbool,默认为 True
是否应将对象数据类型转换为最佳可能的类型。
convert_stringbool,默认为 True
是否应将对象数据类型转换为StringDtype()
。
convert_integerbool,默认为 True
是否,如果可能的话,可以将其转换为整数扩展类型。
convert_booleanbool,默认为 True
是否应将对象数据类型转换为BooleanDtypes()
。
convert_floatingbool,默认为 True
是否,如果可能的话,可以将其转换为浮点扩展类型。如果convert_integer
也为True
,则优先考虑整数数据类型,如果浮点数可以被准确地转换为整数。
dtype_backend,默认为‘numpy_nullable’
应用于结果DataFrame
的后端数据类型(仍处于实验阶段)。行为如下:
-
"numpy_nullable"
:返回可空 dtype 支持的DataFrame
(默认)。 -
"pyarrow"
:返回 pyarrow 支持的可空ArrowDtype
DataFrame。
新版本 2.0 中新增。
返回:
Series 或 DataFrame
具有新数据类型的输入对象的副本。
另请参见
推断对象的数据类型。
将参数转换为日期时间。
将参数转换为时间差。
将参数转换为数值类型。
注意事项
默认情况下,convert_dtypes
将尝试将 Series(或 DataFrame 中的每个 Series)转换为支持pd.NA
的数据类型。通过使用选项convert_string
、convert_integer
、convert_boolean
和convert_floating
,可以分别关闭到StringDtype
、整数扩展类型、BooleanDtype
或浮点扩展类型的单个转换。
对于对象数据类型的列,如果infer_objects
为True
,则使用与正常 Series/DataFrame 构造过程相同的推断规则。然后,如果可能,转换为StringDtype
、BooleanDtype
或适当的整数或浮点扩展类型,否则保持为object
。
如果 dtype 是整数,则转换为适当的整数扩展类型。
如果 dtype 是数值型,并且由全部整数组成,则转换为适当的整数扩展类型。否则,转换为适当的浮点扩展类型。
将来,随着添加支持pd.NA
的新数据类型,此方法的结果将会改变以支持这些新数据类型。
例子
>>> df = pd.DataFrame(
... {
... "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
... "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")),
... "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")),
... "d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")),
... "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")),
... "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),
... }
... )
从具有默认数据类型的 DataFrame 开始。
>>> df
a b c d e f
0 1 x True h 10.0 NaN
1 2 y False i NaN 100.5
2 3 z NaN NaN 20.0 200.0
>>> df.dtypes
a int32
b object
c object
d object
e float64
f float64
dtype: object
将 DataFrame 转换为使用最佳可能的数据类型。
>>> dfn = df.convert_dtypes()
>>> dfn
a b c d e f
0 1 x True h 10 <NA>
1 2 y False i <NA> 100.5
2 3 z <NA> <NA> 20 200.0
>>> dfn.dtypes
a Int32
b string[python]
c boolean
d string[python]
e Int64
f Float64
dtype: object
从字符串序列和由np.nan
表示的缺失数据开始。
>>> s = pd.Series(["a", "b", np.nan])
>>> s
0 a
1 b
2 NaN
dtype: object
获得一个具有StringDtype
数据类型的序列。
>>> s.convert_dtypes()
0 a
1 b
2 <NA>
dtype: string
pandas.Series.infer_objects
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.infer_objects.html
Series.infer_objects(copy=None)
尝试推断对象列的更好数据类型。
尝试对对象类型的列进行软转换,保持非对象和无法转换的列不变。推断规则与正常 Series/DataFrame 构建时相同。
参数:
copybool,默认为 True
是否为非对象或无法推断的列或 Series 进行复制。
注意
使用copy
关键字将在 pandas 3.0 中改变行为。写时复制将默认启用,这意味着所有带有copy
关键字的方法将使用延迟复制机制来推迟复制并忽略copy
关键字。copy
关键字将在未来版本的 pandas 中被移除。
通过启用写时复制pd.options.mode.copy_on_write = True
,您已经可以获得未来的行为和改进。
返回:
与输入对象相同的类型
参见
to_datetime
将参数转换为日期时间。
to_timedelta
将参数转换为时间间隔。
to_numeric
将参数转换为数值类型。
convert_dtypes
将参数转换为最佳可能的数据类型。
示例
>>> df = pd.DataFrame({"A": ["a", 1, 2, 3]})
>>> df = df.iloc[1:]
>>> df
A
1 1
2 2
3 3
>>> df.dtypes
A object
dtype: object
>>> df.infer_objects().dtypes
A int64
dtype: object
pandas.Series.copy
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.copy.html
Series.copy(deep=True)
复制此对象的索引和数据。
当deep=True
(默认值)时,将创建一个新对象,其中包含调用对象的数据和索引的副本。对副本的数据或索引的修改将不会反映在原始对象中(请参阅下面的说明)。
当deep=False
时,将创建一个新对象,而不会复制调用对象的数据或索引(只会复制到数据和索引的引用)。对原始数据的任何更改都将反映在浅拷贝中(反之亦然)。
注意
上述描述的deep=False
行为将在 pandas 3.0 中发生变化。写时复制将默认启用,这意味着返回deep=False
的“浅”拷贝仍将避免进行急切拷贝,但原始数据的更改将不再反映在浅拷贝中(反之亦然)。相反,它利用了一种懒惰(延迟)拷贝机制,只有在对原始数据或浅拷贝进行任何更改时才会复制数据。
您已经可以通过启用写时复制pd.options.mode.copy_on_write = True
来获得未来的行为和改进。
参数:
deepbool,默认为 True
进行深度复制,包括数据和索引的复制。使用deep=False
时,索引和数据都不会被复制。
返回:
Series 或 DataFrame
对象类型与调用者匹配。
说明
当deep=True
时,数据会被复制,但实际的 Python 对象不会被递归复制,只会复制到对象的引用。这与标准库中的 copy.deepcopy 不同,后者会递归复制对象数据(请参阅下面的示例)。
当deep=True
时,Index
对象会被复制,但出于性能原因,底层 numpy 数组不会被复制。由于Index
是不可变的,底层数据可以安全共享,因此不需要复制。
由于 pandas 不是线程安全的,请参阅在线程环境中复制时的注意事项。
当 pandas 配置中的copy_on_write
设置为True
时,即使deep=False
,copy_on_write
配置也会生效。这意味着对复制数据的任何更改都会在写入时生成数据的新副本(反之亦然)。对原始变量或复制变量进行的任何更改都不会反映在对方中。请参阅写时复制获取更多信息。
示例
>>> s = pd.Series([1, 2], index=["a", "b"])
>>> s
a 1
b 2
dtype: int64
>>> s_copy = s.copy()
>>> s_copy
a 1
b 2
dtype: int64
浅拷贝与默认(深拷贝)的区别:
>>> s = pd.Series([1, 2], index=["a", "b"])
>>> deep = s.copy()
>>> shallow = s.copy(deep=False)
浅拷贝与原始共享数据和索引。
>>> s is shallow
False
>>> s.values is shallow.values and s.index is shallow.index
True
深拷贝具有自己的数据和索引的副本。
>>> s is deep
False
>>> s.values is deep.values or s.index is deep.index
False
对由浅拷贝和原始共享的数据的更新在两者中都会反映出来(注意:对于 pandas >= 3.0,这将不再是真实的);深拷贝保持不变。
>>> s.iloc[0] = 3
>>> shallow.iloc[1] = 4
>>> s
a 3
b 4
dtype: int64
>>> shallow
a 3
b 4
dtype: int64
>>> deep
a 1
b 2
dtype: int64
请注意,当复制包含 Python 对象的对象时,深拷贝会复制数据,但不会递归地这样做。更新嵌套数据对象将反映在深拷贝中。
>>> s = pd.Series([[1, 2], [3, 4]])
>>> deep = s.copy()
>>> s[0][0] = 10
>>> s
0 [10, 2]
1 [3, 4]
dtype: object
>>> deep
0 [10, 2]
1 [3, 4]
dtype: object
Copy-on-Write 设置为 true,当原始数据发生更改时,浅拷贝不会被修改:
>>> with pd.option_context("mode.copy_on_write", True):
... s = pd.Series([1, 2], index=["a", "b"])
... copy = s.copy(deep=False)
... s.iloc[0] = 100
... s
a 100
b 2
dtype: int64
>>> copy
a 1
b 2
dtype: int64
pandas.Series.bool
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.bool.html
Series.bool()
返回单个元素 Series 或 DataFrame 的布尔值。
自版本 2.1.0 起已弃用:布尔值已弃用,并将在未来版本的 pandas 中移除。对于Series
,请使用pandas.Series.item
。
这必须是一个布尔标量值,要么为 True,要么为 False。如果 Series 或 DataFrame 不具有确切的 1 个元素,或该元素不是布尔值(整数值 0 和 1 也将引发异常),则会引发 ValueError。
返回:
布尔值
Series 或 DataFrame 中的值。
另请参见
Series.astype
更改 Series 的数据类型,包括布尔值。
DataFrame.astype
更改 DataFrame 的数据类型,包括布尔值。
NumPy 布尔数据类型,由 pandas 用于布尔值。
示例
该方法仅适用于具有布尔值的单元素对象:
>>> pd.Series([True]).bool()
True
>>> pd.Series([False]).bool()
False
>>> pd.DataFrame({'col': [True]}).bool()
True
>>> pd.DataFrame({'col': [False]}).bool()
False
这是一种替代方法,仅适用于具有布尔值的单元素对象:
>>> pd.Series([True]).item()
True
>>> pd.Series([False]).item()
False
pandas.Series.to_numpy
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.to_numpy.html
Series.to_numpy(dtype=None, copy=False, na_value=_NoDefault.no_default, **kwargs)
表示此 Series 或 Index 中的值的 NumPy ndarray。
参数:
dtypestr 或 numpy.dtype,可选
传递给numpy.asarray()
的 dtype。
copybool,默认为 False
是否确保返回的值不是另一个数组的视图。请注意,copy=False
并不确保to_numpy()
是无副本的。相反,copy=True
确保进行复制,即使不是绝对必要。
na_value任意,可选
用于缺失值的值。默认值取决于 dtype 和数组的类型。
**kwargs
传递给底层数组的to_numpy
方法的其他关键字(用于扩展数组)。
返回:
numpy.ndarray
另请参阅
Series.array
获取实际存储的数据。
Index.array
获取实际存储的数据。
DataFrame.to_numpy
DataFrame 的类似方法。
注意
返回的数组将相等(self 中相等的值在返回的数组中也相等;不相等的值也是如此)。当 self 包含 ExtensionArray 时,dtype 可能不同。例如,对于 category-dtype Series,to_numpy()
将返回一个 NumPy 数组,分类 dtype 将丢失。
对于 NumPy dtypes,这将是对存储在此 Series 或 Index 中的实际数据的引用(假设copy=False
)。在原地修改结果将修改存储在 Series 或 Index 中的数据(我们不建议这样做)。
对于扩展类型,to_numpy()
可能需要复制数据并将结果强制转换为 NumPy 类型(可能是对象),这可能很昂贵。当您需要对底层数据进行无副本引用时,应改用Series.array
。
该表列出了不同的 dtype 和各种 pandas 中各种 dtype 的to_numpy()
的默认返回类型。
dtype | 数组类型 |
---|---|
category[T] | ndarray[T](与输入相同的 dtype) |
period | ndarray[object](周期) |
interval | ndarray[object](间隔) |
IntegerNA | ndarray[object] |
datetime64[ns] | datetime64[ns] |
datetime64[ns, tz] | ndarray[object](时间戳) |
示例
>>> ser = pd.Series(pd.Categorical(['a', 'b', 'a']))
>>> ser.to_numpy()
array(['a', 'b', 'a'], dtype=object)
指定 dtype 以控制如何表示 datetime-aware 数据。使用dtype=object
返回一个包含正确tz
的 pandas Timestamp
对象的 ndarray。
>>> ser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))
>>> ser.to_numpy(dtype=object)
array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'),
Timestamp('2000-01-02 00:00:00+0100', tz='CET')],
dtype=object)
或dtype='datetime64[ns]'
以返回本机 datetime64 值的 ndarray。值将转换为 UTC 并丢弃时区信息。
>>> ser.to_numpy(dtype="datetime64[ns]")
...
array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00...'],
dtype='datetime64[ns]')
pandas.Series.to_period
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.to_period.html
Series.to_period(freq=None, copy=None)
将 Series 从 DatetimeIndex 转换为 PeriodIndex。
参数:
freqstr,默认为 None
与 PeriodIndex 相关的频率。
copybool,默认为 True
是否返回副本。
注意
在 pandas 3.0 中,copy 关键字的行为将发生变化。写时复制将默认启用,这意味着所有带有 copy 关键字的方法将使用延迟复制机制来推迟复制并忽略 copy 关键字。copy 关键字将在未来的 pandas 版本中被移除。
通过启用写时复制pd.options.mode.copy_on_write = True
,您已经可以获得未来的行为和改进。
返回:
系列
将索引转换为 PeriodIndex 的 Series。
示例
>>> idx = pd.DatetimeIndex(['2023', '2024', '2025'])
>>> s = pd.Series([1, 2, 3], index=idx)
>>> s = s.to_period()
>>> s
2023 1
2024 2
2025 3
Freq: Y-DEC, dtype: int64
查看索引
>>> s.index
PeriodIndex(['2023', '2024', '2025'], dtype='period[Y-DEC]')
pandas.Series.to_timestamp
译文:
pandas.pydata.org/docs/reference/api/pandas.Series.to_timestamp.html
Series.to_timestamp(freq=None, how='start', copy=None)
转换为时间戳的 DatetimeIndex,在周期的开始。
参数:
freqstr,默认为 PeriodIndex 的频率
所需的频率。
how
将周期转换为时间戳的惯例;周期的开始与结束。
copybool,默认为 True
是否返回副本。
注意
在 pandas 3.0 中,copy 关键字的行为将发生变化。写时复制将默认启用,这意味着所有带有 copy 关键字的方法将使用延迟复制机制来推迟复制并忽略 copy 关键字。copy 关键字将在未来的 pandas 版本中被移除。
通过启用写时复制pd.options.mode.copy_on_write = True
,您已经可以获得未来的行为和改进。
返回:
具有 DatetimeIndex 的 Series
示例
>>> idx = pd.PeriodIndex(['2023', '2024', '2025'], freq='Y')
>>> s1 = pd.Series([1, 2, 3], index=idx)
>>> s1
2023 1
2024 2
2025 3
Freq: Y-DEC, dtype: int64
时间戳的结果频率为 YearBegin。
>>> s1 = s1.to_timestamp()
>>> s1
2023-01-01 1
2024-01-01 2
2025-01-01 3
Freq: YS-JAN, dtype: int64
使用偏移量作为时间戳的频率。
>>> s2 = pd.Series([1, 2, 3], index=idx)
>>> s2 = s2.to_timestamp(freq='M')
>>> s2
2023-01-31 1
2024-01-31 2
2025-01-31 3
Freq: YE-JAN, dtype: int64
pandas.Series.to_list
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.to_list.html
Series.to_list()
返回值列表。
这些都是标量类型,即 Python 标量(对于 str、int、float)或 pandas 标量(对于 Timestamp/Timedelta/Interval/Period)。
返回:
列表
另请参阅
将数组作为 Python 标量的 a.ndim 级别深度嵌套列表返回。
示例
对于 Series
>>> s = pd.Series([1, 2, 3])
>>> s.to_list()
[1, 2, 3]
对于索引:
>>> idx = pd.Index([1, 2, 3])
>>> idx
Index([1, 2, 3], dtype='int64')
>>> idx.to_list()
[1, 2, 3]
pandas.Series.__array__
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.__array__.html
Series.__array__(dtype=None, copy=None)
将值作为 NumPy 数组返回。
用户不应直接调用此函数。而是由 numpy.array()
和 numpy.asarray()
调用。
参数:
dtypestr 或 numpy.dtype,可选
用于生成结果 NumPy 数组的 dtype。默认情况下,dtype 是从数据中推断出来的。
copybool 或 None,可选
未使用。
返回:
numpy.ndarray
将系列中的值转换为具有指定 dtype 的 numpy.ndarray
。
另请参阅
array
从数据创建一个新的数组。
Series.array
返回 Series 支持的数组的零拷贝视图。
Series.to_numpy
与 Series 方法具有类似行为。
示例
>>> ser = pd.Series([1, 2, 3])
>>> np.asarray(ser)
array([1, 2, 3])
对于时区感知数据,可以使用 dtype='object'
保留时区。
>>> tzser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))
>>> np.asarray(tzser, dtype="object")
array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'),
Timestamp('2000-01-02 00:00:00+0100', tz='CET')],
dtype=object)
或者将值本地化为 UTC 并丢弃 tzinfo,并使用 dtype='datetime64[ns]'
>>> np.asarray(tzser, dtype="datetime64[ns]")
array(['1999-12-31T23:00:00.000000000', ...],
dtype='datetime64[ns]')
pandas.Series.get
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.get.html
Series.get(key, default=None)
从对象中获取给定键(例如:DataFrame 列)的项目。
如果未找到,则返回默认值。
参数:
key对象
返回:
与对象中包含的项目相同类型
示例
>>> df = pd.DataFrame(
... [
... [24.3, 75.7, "high"],
... [31, 87.8, "high"],
... [22, 71.6, "medium"],
... [35, 95, "medium"],
... ],
... columns=["temp_celsius", "temp_fahrenheit", "windspeed"],
... index=pd.date_range(start="2014-02-12", end="2014-02-15", freq="D"),
... )
>>> df
temp_celsius temp_fahrenheit windspeed
2014-02-12 24.3 75.7 high
2014-02-13 31.0 87.8 high
2014-02-14 22.0 71.6 medium
2014-02-15 35.0 95.0 medium
>>> df.get(["temp_celsius", "windspeed"])
temp_celsius windspeed
2014-02-12 24.3 high
2014-02-13 31.0 high
2014-02-14 22.0 medium
2014-02-15 35.0 medium
>>> ser = df['windspeed']
>>> ser.get('2014-02-13')
'high'
如果未找到键,则将使用默认值。
>>> df.get(["temp_celsius", "temp_kelvin"], default="default_value")
'default_value'
>>> ser.get('2014-02-10', '[unknown]')
'[unknown]'
pandas.Series.at
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.at.html
property Series.at
通过行/列标签对访问单个值。
与loc
类似,两者都提供基于标签的查找。如果您只需要在 DataFrame 或 Series 中获取或设置单个值,请使用at
。
引发:
键错误
如果在 DataFrame 或 Series 中获取一个值而“标签”不存在。
值错误
如果行/列标签对不是元组,或者对于 DataFrame,对于任何标签,如果标签不是标量。 如果标签是类似列表的(不包括命名元组)。
另请参阅
DataFrame.at
通过标签访问行/列对的单个值。
DataFrame.iat
通过整数位置访问行/列对的单个值。
DataFrame.loc
通过标签访问一组行和列。
DataFrame.iloc
通过整数位置访问一组行和列。
Series.at
通过标签访问单个值。
Series.iat
通过整数位置访问单个值。
Series.loc
通过标签访问一组行。
Series.iloc
通过整数位置访问一组行。
注意
有关更多详细信息,请参见快速标量值获取和设置。
示例
>>> df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]],
... index=[4, 5, 6], columns=['A', 'B', 'C'])
>>> df
A B C
4 0 2 3
5 0 4 1
6 10 20 30
获取指定行/列对的值
>>> df.at[4, 'B']
2
在指定的行/列对设置值
>>> df.at[4, 'B'] = 10
>>> df.at[4, 'B']
10
获取 Series 中的值
>>> df.loc[5].at['B']
4
pandas.Series.iat
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.iat.html
property Series.iat
通过整数位置访问行/列对的单个值。
与 iloc
类似,都提供基于整数的查找。如果您只需要在 DataFrame 或 Series 中获取或设置单个值,请使用 iat
。
引发:
索引错误
当整数位置超出范围时。
另请参阅
DataFrame.at
访问行/列标签对的单个值。
DataFrame.loc
通过标签访问一组行和列。
DataFrame.iloc
通过整数位置访问一组行和列。
示例
>>> df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]],
... columns=['A', 'B', 'C'])
>>> df
A B C
0 0 2 3
1 0 4 1
2 10 20 30
获取指定行/列对处的值
>>> df.iat[1, 2]
1
设置指定行/列对处的值
>>> df.iat[1, 2] = 10
>>> df.iat[1, 2]
10
获取系列内的值
>>> df.loc[0].iat[1]
2
pandas.Series.loc
原文:
pandas.pydata.org/docs/reference/api/pandas.Series.loc.html
property Series.loc
通过标签或布尔数组访问一组行和列。
.loc[]
主要基于标签,但也可以与布尔数组一起使用。
允许的输入为:
-
单个标签,例如
5
或'a'
,(请注意5
被解释为索引的标签,never
被解释为索引上的整数位置)。 -
标签列表或数组,例如
['a', 'b', 'c']
。 -
具有标签的切片对象,例如
'a':'f'
。警告
请注意,与通常的 Python 切片相反,起始和结束都包括在内
-
与被切片轴长度相同的布尔数组,例如
[True, False, True]
。 -
可对齐的布尔 Series。在掩码之前,键的索引将被对齐。
-
可对齐的索引。返回选择的索引将是输入的索引。
-
具有一个参数(调用的 Series 或 DataFrame)的
callable
函数,并返回用于索引的有效输出(上述之一)
请参阅按标签选择了解更多信息。
引发:
KeyError
如果找不到任何项。
索引错误
如果传递了索引键并且其索引与框架索引不对齐。
另请参见
DataFrame.at
访问行/列标签对的单个值。
DataFrame.iloc
通过整数位置访问一组行和列。
DataFrame.xs
从 Series/DataFrame 返回横截面(行或列)。
Series.loc
使用标签访问一组值。
示例
获取值
>>> df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
... index=['cobra', 'viper', 'sidewinder'],
... columns=['max_speed', 'shield'])
>>> df
max_speed shield
cobra 1 2
viper 4 5
sidewinder 7 8
单个标签。请注意,这将返回行作为 Series。
>>> df.loc['viper']
max_speed 4
shield 5
Name: viper, dtype: int64
标签列表。注意使用[[]]
会返回一个 DataFrame。
>>> df.loc[['viper', 'sidewinder']]
max_speed shield
viper 4 5
sidewinder 7 8
行和列的单个标签
>>> df.loc['cobra', 'shield']
2
使用行标签和列的单个标签进行切片。如上所述,请注意切片的起始和结束都包括在内。
>>> df.loc['cobra':'viper', 'max_speed']
cobra 1
viper 4
Name: max_speed, dtype: int64
与行轴长度相同的布尔列表
>>> df.loc[[False, False, True]]
max_speed shield
sidewinder 7 8
可对齐的布尔 Series:
>>> df.loc[pd.Series([False, True, False],
... index=['viper', 'sidewinder', 'cobra'])]
max_speed shield
sidewinder 7 8
索引(与df.reindex
的行为相同)
>>> df.loc[pd.Index(["cobra", "viper"], name="foo")]
max_speed shield
foo
cobra 1 2
viper 4 5
返回布尔 Series 的条件
>>> df.loc[df['shield'] > 6]
max_speed shield
sidewinder 7 8
返回指定列标签的布尔 Series 的条件
>>> df.loc[df['shield'] > 6, ['max_speed']]
max_speed
sidewinder 7
使用&
进行多条件筛选,返回布尔 Series
>>> df.loc[(df['max_speed'] > 1) & (df['shield'] < 8)]
max_speed shield
viper 4 5
使用|
进行多条件筛选,返回布尔 Series
>>> df.loc[(df['max_speed'] > 4) | (df['shield'] < 5)]
max_speed shield
cobra 1 2
sidewinder 7 8
请确保每个条件都用括号()
括起来。有关更多详细信息和布尔索引解释,请参阅用户指南。
注意
如果您发现自己在.loc[]
中使用 3 个或更多条件,请考虑使用高级索引。
请参阅在多级索引 DataFrame 上使用.loc[]
。
返回布尔 Series 的可调用函数
>>> df.loc[lambda df: df['shield'] == 8]
max_speed shield
sidewinder 7 8
设置值
为匹配标签列表的所有项设置值
>>> df.loc[['viper', 'sidewinder'], ['shield']] = 50
>>> df
max_speed shield
cobra 1 2
viper 4 50
sidewinder 7 50
为整行设置值
>>> df.loc['cobra'] = 10
>>> df
max_speed shield
cobra 10 10
viper 4 50
sidewinder 7 50
为整个列设置值
>>> df.loc[:, 'max_speed'] = 30
>>> df
max_speed shield
cobra 30 10
viper 30 50
sidewinder 30 50
为匹配可调用条件的行设置值
>>> df.loc[df['shield'] > 35] = 0
>>> df
max_speed shield
cobra 30 10
viper 0 0
sidewinder 0 0
添加匹配位置的值
>>> df.loc["viper", "shield"] += 5
>>> df
max_speed shield
cobra 30 10
viper 0 5
sidewinder 0 0
使用Series
或DataFrame
进行设置会匹配索引标签的值,而不是索引位置。
>>> shuffled_df = df.loc[["viper", "cobra", "sidewinder"]]
>>> df.loc[:] += shuffled_df
>>> df
max_speed shield
cobra 60 20
viper 0 10
sidewinder 0 0
获取具有整数标签的 DataFrame 上的值
另一个使用整数索引的示例
>>> df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
... index=[7, 8, 9], columns=['max_speed', 'shield'])
>>> df
max_speed shield
7 1 2
8 4 5
9 7 8
使用整数标签对行进行切片。如上所述,请注意切片的起始和结束都包括在内。
>>> df.loc[7:9]
max_speed shield
7 1 2
8 4 5
9 7 8
使用 MultiIndex 获取值
使用具有 MultiIndex 的 DataFrame 的多个示例
>>> tuples = [
... ('cobra', 'mark i'), ('cobra', 'mark ii'),
... ('sidewinder', 'mark i'), ('sidewinder', 'mark ii'),
... ('viper', 'mark ii'), ('viper', 'mark iii')
... ]
>>> index = pd.MultiIndex.from_tuples(tuples)
>>> values = [[12, 2], [0, 4], [10, 20],
... [1, 4], [7, 1], [16, 36]]
>>> df = pd.DataFrame(values, columns=['max_speed', 'shield'], index=index)
>>> df
max_speed shield
cobra mark i 12 2
mark ii 0 4
sidewinder mark i 10 20
mark ii 1 4
viper mark ii 7 1
mark iii 16 36
单个标签。请注意,这将返回一个具有单个索引的 DataFrame。
>>> df.loc['cobra']
max_speed shield
mark i 12 2
mark ii 0 4
单索引元组。请注意,这将返回一个 Series。
>>> df.loc[('cobra', 'mark ii')]
max_speed 0
shield 4
Name: (cobra, mark ii), dtype: int64
单行和列的单个标签。类似于传入元组,这将返回一个 Series。
>>> df.loc['cobra', 'mark i']
max_speed 12
shield 2
Name: (cobra, mark i), dtype: int64
单个元组。请注意,使用[[]]
将返回一个 DataFrame。
>>> df.loc[[('cobra', 'mark ii')]]
max_speed shield
cobra mark ii 0 4
索引的单个元组与单个列标签
>>> df.loc[('cobra', 'mark i'), 'shield']
2
从索引元组到单个标签的切片
>>> df.loc[('cobra', 'mark i'):'viper']
max_speed shield
cobra mark i 12 2
mark ii 0 4
sidewinder mark i 10 20
mark ii 1 4
viper mark ii 7 1
mark iii 16 36
从索引元组到索引元组的切片
>>> df.loc[('cobra', 'mark i'):('viper', 'mark ii')]
max_speed shield
cobra mark i 12 2
mark ii 0 4
sidewinder mark i 10 20
mark ii 1 4
viper mark ii 7 1
请参阅用户指南以获取更多关于高级索引的详细信息和解释。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
2023-06-26 Bert Pytorch 源码分析:五、模型架构简图
2023-06-26 Bert Pytorch 源码分析:四、编解码器
2023-06-26 Bert Pytorch 源码分析:三、Transformer块
2020-06-26 PythonGuru 中文系列教程·翻译完成