Pandas-2-2-中文文档-三十六-
Pandas 2.2 中文文档(三十六)
pandas.core.resample.Resampler.__iter__
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.__iter__.html
Resampler.__iter__()
分组迭代器。
返回:
生成器,产生(名称,子集对象)的序列
对于每个分组
示例
对于 SeriesGroupBy:
>>> lst = ['a', 'a', 'b']
>>> ser = pd.Series([1, 2, 3], index=lst)
>>> ser
a 1
a 2
b 3
dtype: int64
>>> for x, y in ser.groupby(level=0):
... print(f'{x}\n{y}\n')
a
a 1
a 2
dtype: int64
b
b 3
dtype: int64
对于 DataFrameGroupBy:
>>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
>>> df = pd.DataFrame(data, columns=["a", "b", "c"])
>>> df
a b c
0 1 2 3
1 1 5 6
2 7 8 9
>>> for x, y in df.groupby(by=["a"]):
... print(f'{x}\n{y}\n')
(1,)
a b c
0 1 2 3
1 1 5 6
(7,)
a b c
2 7 8 9
对于 Resampler:
>>> ser = pd.Series([1, 2, 3, 4], index=pd.DatetimeIndex(
... ['2023-01-01', '2023-01-15', '2023-02-01', '2023-02-15']))
>>> ser
2023-01-01 1
2023-01-15 2
2023-02-01 3
2023-02-15 4
dtype: int64
>>> for x, y in ser.resample('MS'):
... print(f'{x}\n{y}\n')
2023-01-01 00:00:00
2023-01-01 1
2023-01-15 2
dtype: int64
2023-02-01 00:00:00
2023-02-01 3
2023-02-15 4
dtype: int64
pandas.core.resample.Resampler.groups
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.groups.html
property Resampler.groups
字典 {组名 -> 组标签}。
示例
对于 SeriesGroupBy:
>>> lst = ['a', 'a', 'b']
>>> ser = pd.Series([1, 2, 3], index=lst)
>>> ser
a 1
a 2
b 3
dtype: int64
>>> ser.groupby(level=0).groups
{'a': ['a', 'a'], 'b': ['b']}
对于 DataFrameGroupBy:
>>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
>>> df = pd.DataFrame(data, columns=["a", "b", "c"])
>>> df
a b c
0 1 2 3
1 1 5 6
2 7 8 9
>>> df.groupby(by=["a"]).groups
{1: [0, 1], 7: [2]}
对于 Resampler:
>>> ser = pd.Series([1, 2, 3, 4], index=pd.DatetimeIndex(
... ['2023-01-01', '2023-01-15', '2023-02-01', '2023-02-15']))
>>> ser
2023-01-01 1
2023-01-15 2
2023-02-01 3
2023-02-15 4
dtype: int64
>>> ser.resample('MS').groups
{Timestamp('2023-01-01 00:00:00'): 2, Timestamp('2023-02-01 00:00:00'): 4}
pandas.core.resample.Resampler.indices
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.indices.html
property Resampler.indices
字典 {组名 -> 组索引}。
示例
对于 SeriesGroupBy:
>>> lst = ['a', 'a', 'b']
>>> ser = pd.Series([1, 2, 3], index=lst)
>>> ser
a 1
a 2
b 3
dtype: int64
>>> ser.groupby(level=0).indices
{'a': array([0, 1]), 'b': array([2])}
对于 DataFrameGroupBy:
>>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
>>> df = pd.DataFrame(data, columns=["a", "b", "c"],
... index=["owl", "toucan", "eagle"])
>>> df
a b c
owl 1 2 3
toucan 1 5 6
eagle 7 8 9
>>> df.groupby(by=["a"]).indices
{1: array([0, 1]), 7: array([2])}
对于 Resampler:
>>> ser = pd.Series([1, 2, 3, 4], index=pd.DatetimeIndex(
... ['2023-01-01', '2023-01-15', '2023-02-01', '2023-02-15']))
>>> ser
2023-01-01 1
2023-01-15 2
2023-02-01 3
2023-02-15 4
dtype: int64
>>> ser.resample('MS').indices
defaultdict(<class 'list'>, {Timestamp('2023-01-01 00:00:00'): [0, 1],
Timestamp('2023-02-01 00:00:00'): [2, 3]})
pandas.core.resample.Resampler.get_group
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.get_group.html
Resampler.get_group(name, obj=None)
使用提供的名称构建 DataFrame 组。
参数:
name对象
要作为 DataFrame 获取的组的名称。
objDataFrame,默认为 None
要从中获取 DataFrame 的 DataFrame。如果为 None,则将使用调用 groupby 的对象。
自 2.1.0 版本起已弃用:obj 已弃用,并将在将来的版本中删除。请使用 df.iloc[gb.indices.get(name)]
替代 gb.get_group(name, obj=df)
。
返回:
与 obj 相同类型
示例
对于 SeriesGroupBy:
>>> lst = ['a', 'a', 'b']
>>> ser = pd.Series([1, 2, 3], index=lst)
>>> ser
a 1
a 2
b 3
dtype: int64
>>> ser.groupby(level=0).get_group("a")
a 1
a 2
dtype: int64
对于 DataFrameGroupBy:
>>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
>>> df = pd.DataFrame(data, columns=["a", "b", "c"],
... index=["owl", "toucan", "eagle"])
>>> df
a b c
owl 1 2 3
toucan 1 5 6
eagle 7 8 9
>>> df.groupby(by=["a"]).get_group((1,))
a b c
owl 1 2 3
toucan 1 5 6
对于 Resampler:
>>> ser = pd.Series([1, 2, 3, 4], index=pd.DatetimeIndex(
... ['2023-01-01', '2023-01-15', '2023-02-01', '2023-02-15']))
>>> ser
2023-01-01 1
2023-01-15 2
2023-02-01 3
2023-02-15 4
dtype: int64
>>> ser.resample('MS').get_group('2023-01-01')
2023-01-01 1
2023-01-15 2
dtype: int64
pandas.core.resample.Resampler.apply
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.apply.html
Resampler.apply(func=None, *args, **kwargs)
在指定轴上使用一个或多个操作进行聚合。
参数:
func函数、字符串、列表或字典
用于聚合数据的函数。如果是函数,则必须在传递给 DataFrame 或传递给 DataFrame.apply 时起作用。
可接受的组合有:
-
函数
-
字符串函数名称
-
函数列表和/或函数名称,例如
[np.sum, 'mean']
-
轴标签的字典 -> 函数、函数名称或此类列表。
*args
传递给函数的位置参数。
**kwargs
传递给函数的关键字参数。
返回:
标量、Series 或 DataFrame
返回可以是:
-
标量:当使用单个函数调用 Series.agg 时
-
Series:当使用单个函数调用 DataFrame.agg 时
-
DataFrame:当使用多个函数调用 DataFrame.agg 时
另请参阅
DataFrame.groupby.aggregate
使用可调用函数、字符串、字典或字符串/可调用函数列表进行聚合。
DataFrame.resample.transform
根据给定函数在每个组上转换 Series。
DataFrame.aggregate
在指定轴上使用一个或多个操作进行聚合。
注意事项
聚合操作始终在一个轴上执行,可以是索引(默认)或列轴。这种行为与 numpy 聚合函数(mean、median、prod、sum、std、var)不同,numpy 聚合函数的默认行为是计算平坦数组的聚合,例如,numpy.mean(arr_2d)
而不是 numpy.mean(arr_2d, axis=0)
。
agg 是 aggregate 的别名。请使用别名。
可能会产生意外行为或错误的会改变传递对象的函数不受支持。有关更多详细信息,请参阅 使用用户定义函数 (UDF) 进行变异。
传递的用户定义函数将传递一个 Series 进行评估。
示例
>>> s = pd.Series([1, 2, 3, 4, 5],
... index=pd.date_range('20130101', periods=5, freq='s'))
>>> s
2013-01-01 00:00:00 1
2013-01-01 00:00:01 2
2013-01-01 00:00:02 3
2013-01-01 00:00:03 4
2013-01-01 00:00:04 5
Freq: s, dtype: int64
>>> r = s.resample('2s')
>>> r.agg("sum")
2013-01-01 00:00:00 3
2013-01-01 00:00:02 7
2013-01-01 00:00:04 5
Freq: 2s, dtype: int64
>>> r.agg(['sum', 'mean', 'max'])
sum mean max
2013-01-01 00:00:00 3 1.5 2
2013-01-01 00:00:02 7 3.5 4
2013-01-01 00:00:04 5 5.0 5
>>> r.agg({'result': lambda x: x.mean() / x.std(),
... 'total': "sum"})
result total
2013-01-01 00:00:00 2.121320 3
2013-01-01 00:00:02 4.949747 7
2013-01-01 00:00:04 NaN 5
>>> r.agg(average="mean", total="sum")
average total
2013-01-01 00:00:00 1.5 3
2013-01-01 00:00:02 3.5 7
2013-01-01 00:00:04 5.0 5
pandas.core.resample.Resampler.aggregate
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.aggregate.html
final Resampler.aggregate(func=None, *args, **kwargs)
使用一个或多个操作聚合指定轴上的数据。
参数:
func函数、str、list 或 dict
用于聚合数据的函数。如果是函数,必须在传递给 DataFrame 或传递给 DataFrame.apply 时有效。
接受的组合是:
-
函数
-
字符串函数名称
-
函数列表和/或函数名称,例如
[np.sum, 'mean']
-
轴标签的字典 -> 函数、函数名称或此类列表。
*args
传递给 func 的位置参数。
**kwargs
传递给 func 的关键字参数。
返回:
标量、Series 或 DataFrame
返回值可能是:
-
标量:当 Series.agg 使用单个函数调用时
-
系列:当 DataFrame.agg 使用单个函数调用时
-
DataFrame:当 DataFrame.agg 使用多个函数调用时
另请参阅
DataFrame.groupby.aggregate
使用可调用、字符串、字典或字符串/可调用列表进行聚合。
DataFrame.resample.transform
根据给定的函数转换每个组上的系列。
DataFrame.aggregate
使用一个或多个操作聚合指定的轴上的数据。
注
聚合操作始终在轴上执行,可以是索引(默认)或列轴。这种行为与 numpy 聚合函数(mean、median、prod、sum、std、var)不同,后者默认计算展平数组的聚合,例如,numpy.mean(arr_2d)
与numpy.mean(arr_2d, axis=0)
不同。
agg 是 aggregate 的别名。使用别名。
可变传递的函数可能会产生意外行为或错误,并且不受支持。有关更多详细信息,请参阅使用用户定义函数(UDF)方法进行变异。
传递的用户定义函数将传递一个系列进行评估。
示例
>>> s = pd.Series([1, 2, 3, 4, 5],
... index=pd.date_range('20130101', periods=5, freq='s'))
>>> s
2013-01-01 00:00:00 1
2013-01-01 00:00:01 2
2013-01-01 00:00:02 3
2013-01-01 00:00:03 4
2013-01-01 00:00:04 5
Freq: s, dtype: int64
>>> r = s.resample('2s')
>>> r.agg("sum")
2013-01-01 00:00:00 3
2013-01-01 00:00:02 7
2013-01-01 00:00:04 5
Freq: 2s, dtype: int64
>>> r.agg(['sum', 'mean', 'max'])
sum mean max
2013-01-01 00:00:00 3 1.5 2
2013-01-01 00:00:02 7 3.5 4
2013-01-01 00:00:04 5 5.0 5
>>> r.agg({'result': lambda x: x.mean() / x.std(),
... 'total': "sum"})
result total
2013-01-01 00:00:00 2.121320 3
2013-01-01 00:00:02 4.949747 7
2013-01-01 00:00:04 NaN 5
>>> r.agg(average="mean", total="sum")
average total
2013-01-01 00:00:00 1.5 3
2013-01-01 00:00:02 3.5 7
2013-01-01 00:00:04 5.0 5
pandas.core.resample.Resampler.transform
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.transform.html
final Resampler.transform(arg, *args, **kwargs)
调用函数在每个分组上产生一个类似索引的序列。
返回一个转换后的值序列。
参数:
arg 函数
应用于每个分组。应返回一个具有相同索引的序列。
返回:
Series
示例
>>> s = pd.Series([1, 2],
... index=pd.date_range('20180101',
... periods=2,
... freq='1h'))
>>> s
2018-01-01 00:00:00 1
2018-01-01 01:00:00 2
Freq: h, dtype: int64
>>> resampled = s.resample('15min')
>>> resampled.transform(lambda x: (x - x.mean()) / x.std())
2018-01-01 00:00:00 NaN
2018-01-01 01:00:00 NaN
Freq: h, dtype: float64
pandas.core.resample.Resampler.pipe
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.pipe.html
final Resampler.pipe(func, *args, **kwargs)
将带有参数的 func
应用于此 Resampler 对象,并返回其结果。
当您想要通过链接期望 Series、DataFrames、GroupBy 或 Resampler 对象的函数来提高可读性时,请使用 .pipe。而不是编写
>>> h = lambda x, arg2, arg3: x + 1 - arg2 * arg3
>>> g = lambda x, arg1: x * 5 / arg1
>>> f = lambda x: x ** 4
>>> df = pd.DataFrame([["a", 4], ["b", 5]], columns=["group", "value"])
>>> h(g(f(df.groupby('group')), arg1=1), arg2=2, arg3=3)
您可以编写
>>> (df.groupby('group')
... .pipe(f)
... .pipe(g, arg1=1)
... .pipe(h, arg2=2, arg3=3))
这样更易读。
参数:
func可调用对象或 (可调用对象, 字符串) 元组
要应用于此 Resampler 对象的函数,或者是一个 (callable, data_keyword) 元组,其中 data_keyword 是一个字符串,指示 callable 期望 Resampler 对象的关键字。
args可迭代对象,可选
传递给函数的位置参数。
kwargs字典,可选
传递给函数的关键字参数字典。
返回:
函数的返回类型。
另请参阅
Series.pipe
将带有参数的函数应用于系列。
DataFrame.pipe
将带有参数的函数应用于数据框。
apply
将函数应用于每个组,而不是整个 Resampler 对象。
注意
查看更多这里
示例
>>> df = pd.DataFrame({'A': [1, 2, 3, 4]},
... index=pd.date_range('2012-08-02', periods=4))
>>> df
A
2012-08-02 1
2012-08-03 2
2012-08-04 3
2012-08-05 4
要在一次传递中获取每个 2 天期间最大值和最小值之间的差异,您可以执行
>>> df.resample('2D').pipe(lambda x: x.max() - x.min())
A
2012-08-02 1
2012-08-04 1
pandas.core.resample.Resampler.ffill
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.ffill.html
final Resampler.ffill(limit=None)
向前填充值。
参数:
limitint,可选
填充值的数量限制。
返回:
上采样的 Series。
另请参阅
Series.fillna
使用指定的方法填充 NA/NaN 值。
DataFrame.fillna
使用指定方法填充 NA/NaN 值。
示例
在这里我们只创建一个Series
。
>>> ser = pd.Series([1, 2, 3, 4], index=pd.DatetimeIndex(
... ['2023-01-01', '2023-01-15', '2023-02-01', '2023-02-15']))
>>> ser
2023-01-01 1
2023-01-15 2
2023-02-01 3
2023-02-15 4
dtype: int64
使用 ffill
进行降采样的示例(在重采样后我们有更少的日期):
>>> ser.resample('MS').ffill()
2023-01-01 1
2023-02-01 3
Freq: MS, dtype: int64
使用上采样的 ffill
示例(用前一个值填充新日期):
>>> ser.resample('W').ffill()
2023-01-01 1
2023-01-08 1
2023-01-15 2
2023-01-22 2
2023-01-29 2
2023-02-05 3
2023-02-12 3
2023-02-19 4
Freq: W-SUN, dtype: int64
使用上采样和限制的示例(仅将第一个新日期用前一个值填充):
>>> ser.resample('W').ffill(limit=1)
2023-01-01 1.0
2023-01-08 1.0
2023-01-15 2.0
2023-01-22 2.0
2023-01-29 NaN
2023-02-05 3.0
2023-02-12 NaN
2023-02-19 4.0
Freq: W-SUN, dtype: float64
pandas.core.resample.Resampler.bfill
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.bfill.html
final Resampler.bfill(limit=None)
向后填充重新采样数据中的新缺失值。
在统计学中,插补是用替代值替换缺失数据的过程[1]。在重新采样数据时,可能会出现缺失值(例如,当重新采样频率高于原始频率时)。向后填充将用原始序列中的下一个值替换重新采样数据中出现的 NaN 值。不会修改原始数据中存在的缺失值。
参数:
limitint,可选
填充的值数量限制。
返回:
Series,DataFrame
具有向后填充 NaN 值的上采样 Series 或 DataFrame。
另请参阅
bfill
向后填充的别名。
fillna
使用指定方法填充 NaN 值,可以是‘backfill’。
nearest
从中心开始使用最近邻填充 NaN 值。
ffill
向前填充 NaN 值。
Series.fillna
使用指定方法填充 Series 中的 NaN 值,可以是‘backfill’。
DataFrame.fillna
使用指定方法填充 DataFrame 中的 NaN 值,可以是‘backfill’。
参考
[1]
en.wikipedia.org/wiki/Imputation_(statistics
示例
对 Series 进行重新采样:
>>> s = pd.Series([1, 2, 3],
... index=pd.date_range('20180101', periods=3, freq='h'))
>>> s
2018-01-01 00:00:00 1
2018-01-01 01:00:00 2
2018-01-01 02:00:00 3
Freq: h, dtype: int64
>>> s.resample('30min').bfill()
2018-01-01 00:00:00 1
2018-01-01 00:30:00 2
2018-01-01 01:00:00 2
2018-01-01 01:30:00 3
2018-01-01 02:00:00 3
Freq: 30min, dtype: int64
>>> s.resample('15min').bfill(limit=2)
2018-01-01 00:00:00 1.0
2018-01-01 00:15:00 NaN
2018-01-01 00:30:00 2.0
2018-01-01 00:45:00 2.0
2018-01-01 01:00:00 2.0
2018-01-01 01:15:00 NaN
2018-01-01 01:30:00 3.0
2018-01-01 01:45:00 3.0
2018-01-01 02:00:00 3.0
Freq: 15min, dtype: float64
对具有缺失值的 DataFrame 进行重新采样:
>>> df = pd.DataFrame({'a': [2, np.nan, 6], 'b': [1, 3, 5]},
... index=pd.date_range('20180101', periods=3,
... freq='h'))
>>> df
a b
2018-01-01 00:00:00 2.0 1
2018-01-01 01:00:00 NaN 3
2018-01-01 02:00:00 6.0 5
>>> df.resample('30min').bfill()
a b
2018-01-01 00:00:00 2.0 1
2018-01-01 00:30:00 NaN 3
2018-01-01 01:00:00 NaN 3
2018-01-01 01:30:00 6.0 5
2018-01-01 02:00:00 6.0 5
>>> df.resample('15min').bfill(limit=2)
a b
2018-01-01 00:00:00 2.0 1.0
2018-01-01 00:15:00 NaN NaN
2018-01-01 00:30:00 NaN 3.0
2018-01-01 00:45:00 NaN 3.0
2018-01-01 01:00:00 NaN 3.0
2018-01-01 01:15:00 NaN NaN
2018-01-01 01:30:00 6.0 5.0
2018-01-01 01:45:00 6.0 5.0
2018-01-01 02:00:00 6.0 5.0
pandas.core.resample.Resampler.nearest
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.nearest.html
final Resampler.nearest(limit=None)
使用最近值进行重新采样。
在重新采样数据时,可能会出现缺失值(例如,当重新采样频率高于原始频率时)。最近方法将使用索引值基于序列成员的最近值替换重新采样数据中出现的NaN
值。原始数据中存在的缺失值将不会被修改。如果给定了限制,每个原始值的每个方向只填充这么多值。
参数:
limitint,可选
要填充的值的限制数量。
返回:
Series 或 DataFrame
一个上采样的 Series 或 DataFrame,其中NaN
值被其最近值填充。
另请参阅
backfill
在重新采样数据中向后填充新的缺失值。
pad
向前填充NaN
值。
示例
>>> s = pd.Series([1, 2],
... index=pd.date_range('20180101',
... periods=2,
... freq='1h'))
>>> s
2018-01-01 00:00:00 1
2018-01-01 01:00:00 2
Freq: h, dtype: int64
>>> s.resample('15min').nearest()
2018-01-01 00:00:00 1
2018-01-01 00:15:00 1
2018-01-01 00:30:00 2
2018-01-01 00:45:00 2
2018-01-01 01:00:00 2
Freq: 15min, dtype: int64
限制最近值填充的上采样值数量:
>>> s.resample('15min').nearest(limit=1)
2018-01-01 00:00:00 1.0
2018-01-01 00:15:00 1.0
2018-01-01 00:30:00 NaN
2018-01-01 00:45:00 2.0
2018-01-01 01:00:00 2.0
Freq: 15min, dtype: float64
pandas.core.resample.Resampler.fillna
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.fillna.html
final Resampler.fillna(method, limit=None)
填补由上采样引入的缺失值。
在统计学中,插补是用替代值替换缺失数据的过程[1]。在重新采样数据时,可能会出现缺失值(例如,当重新采样频率高于原始频率时)。
原始数据中存在的缺失值不会被修改。
参数:
method
用于填充重新采样数据中的空洞的方法
-
‘pad’或‘ffill’:使用前一个有效观测值来填补缺口(向前填充)。
-
‘backfill’或‘bfill’:使用下一个有效观测值来填补缺口。
-
‘nearest’:使用最近的有效观测值来填补缺口。
limitint,可选
要填充的连续缺失值的限制。
返回:
Series 或 DataFrame
一个带有填充的缺失值的上采样 Series 或 DataFrame。
另请参阅
bfill
在重新采样数据中向后填充 NaN 值。
ffill
在重新采样数据中向前填充 NaN 值。
nearest
从中心开始使用最近邻居填充重新采样数据中的 NaN 值。
interpolate
使用插值填充 NaN 值。
Series.fillna
使用指定的方法填充 Series 中的 NaN 值,可以是‘bfill’和‘ffill’。
DataFrame.fillna
使用指定方法填充 DataFrame 中的 NaN 值,可以是‘bfill’和‘ffill’。
参考文献
[1]
en.wikipedia.org/wiki/Imputation_(statistics
示例
重新采样 Series:
>>> s = pd.Series([1, 2, 3],
... index=pd.date_range('20180101', periods=3, freq='h'))
>>> s
2018-01-01 00:00:00 1
2018-01-01 01:00:00 2
2018-01-01 02:00:00 3
Freq: h, dtype: int64
如果不填充缺失值,你将得到:
>>> s.resample("30min").asfreq()
2018-01-01 00:00:00 1.0
2018-01-01 00:30:00 NaN
2018-01-01 01:00:00 2.0
2018-01-01 01:30:00 NaN
2018-01-01 02:00:00 3.0
Freq: 30min, dtype: float64
>>> s.resample('30min').fillna("backfill")
2018-01-01 00:00:00 1
2018-01-01 00:30:00 2
2018-01-01 01:00:00 2
2018-01-01 01:30:00 3
2018-01-01 02:00:00 3
Freq: 30min, dtype: int64
>>> s.resample('15min').fillna("backfill", limit=2)
2018-01-01 00:00:00 1.0
2018-01-01 00:15:00 NaN
2018-01-01 00:30:00 2.0
2018-01-01 00:45:00 2.0
2018-01-01 01:00:00 2.0
2018-01-01 01:15:00 NaN
2018-01-01 01:30:00 3.0
2018-01-01 01:45:00 3.0
2018-01-01 02:00:00 3.0
Freq: 15min, dtype: float64
>>> s.resample('30min').fillna("pad")
2018-01-01 00:00:00 1
2018-01-01 00:30:00 1
2018-01-01 01:00:00 2
2018-01-01 01:30:00 2
2018-01-01 02:00:00 3
Freq: 30min, dtype: int64
>>> s.resample('30min').fillna("nearest")
2018-01-01 00:00:00 1
2018-01-01 00:30:00 2
2018-01-01 01:00:00 2
2018-01-01 01:30:00 3
2018-01-01 02:00:00 3
Freq: 30min, dtype: int64
上采样之前存在的缺失值不受影响。
>>> sm = pd.Series([1, None, 3],
... index=pd.date_range('20180101', periods=3, freq='h'))
>>> sm
2018-01-01 00:00:00 1.0
2018-01-01 01:00:00 NaN
2018-01-01 02:00:00 3.0
Freq: h, dtype: float64
>>> sm.resample('30min').fillna('backfill')
2018-01-01 00:00:00 1.0
2018-01-01 00:30:00 NaN
2018-01-01 01:00:00 NaN
2018-01-01 01:30:00 3.0
2018-01-01 02:00:00 3.0
Freq: 30min, dtype: float64
>>> sm.resample('30min').fillna('pad')
2018-01-01 00:00:00 1.0
2018-01-01 00:30:00 1.0
2018-01-01 01:00:00 NaN
2018-01-01 01:30:00 NaN
2018-01-01 02:00:00 3.0
Freq: 30min, dtype: float64
>>> sm.resample('30min').fillna('nearest')
2018-01-01 00:00:00 1.0
2018-01-01 00:30:00 NaN
2018-01-01 01:00:00 NaN
2018-01-01 01:30:00 3.0
2018-01-01 02:00:00 3.0
Freq: 30min, dtype: float64
DataFrame 重新采样是逐列进行的。所有相同的选项都可用。
>>> df = pd.DataFrame({'a': [2, np.nan, 6], 'b': [1, 3, 5]},
... index=pd.date_range('20180101', periods=3,
... freq='h'))
>>> df
a b
2018-01-01 00:00:00 2.0 1
2018-01-01 01:00:00 NaN 3
2018-01-01 02:00:00 6.0 5
>>> df.resample('30min').fillna("bfill")
a b
2018-01-01 00:00:00 2.0 1
2018-01-01 00:30:00 NaN 3
2018-01-01 01:00:00 NaN 3
2018-01-01 01:30:00 6.0 5
2018-01-01 02:00:00 6.0 5
pandas.core.resample.Resampler.asfreq
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.asfreq.html
final Resampler.asfreq(fill_value=None)
返回新频率处的值,基本上是重新索引。
参数:
fill_value 标量,可选
用于缺失值的值,在上采样期间应用(请注意,这不会填充已经存在的 NaN)。
返回:
DataFrame 或 Series
指定频率处的值。
参见
Series.asfreq
将 TimeSeries 转换为指定的频率。
DataFrame.asfreq
将 TimeSeries 转换为指定的频率。
示例
>>> ser = pd.Series([1, 2, 3, 4], index=pd.DatetimeIndex(
... ['2023-01-01', '2023-01-31', '2023-02-01', '2023-02-28']))
>>> ser
2023-01-01 1
2023-01-31 2
2023-02-01 3
2023-02-28 4
dtype: int64
>>> ser.resample('MS').asfreq()
2023-01-01 1
2023-02-01 3
Freq: MS, dtype: int64
pandas.core.resample.Resampler.interpolate
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.interpolate.html
final Resampler.interpolate(method='linear', *, axis=0, limit=None, inplace=False, limit_direction='forward', limit_area=None, downcast=_NoDefault.no_default, **kwargs)
根据不同方法在目标时间戳之间插值数值。
首先将原始索引重新索引为目标时间戳(参见core.resample.Resampler.asfreq()
),然后通过DataFrame.interpolate()
对NaN
值进行插值。
参数:
methodstr,默认为‘linear’
要使用的插值技术。之一:
-
‘linear’:忽略索引,将值视为等间距。这是 MultiIndexes 支持的唯一方法。
-
‘time’:适用于每日及更高分辨率数据,以插值给定长度的间隔。
-
‘index’,‘values’:使用索引的实际数值。
-
‘pad’:使用现有值填充 NaN。
-
‘nearest’,‘zero’,‘slinear’,‘quadratic’,‘cubic’,‘barycentric’,‘polynomial’:传递给 scipy.interpolate.interp1d,而‘spline’传递给 scipy.interpolate.UnivariateSpline。这些方法使用索引的数值。‘polynomial’和‘spline’都要求您还指定一个顺序(int),例如
df.interpolate(method='polynomial', order=5)
。请注意,Pandas 中的 slinear 方法指的是 Scipy 的一阶样条,而不是 Pandas 的一阶样条。 -
‘krogh’,‘piecewise_polynomial’,‘spline’,‘pchip’,‘akima’,‘cubicspline’:类似名称的 SciPy 插值方法的包装器。请参阅注释。
-
‘from_derivatives’:指的是 scipy.interpolate.BPoly.from_derivatives。
axis{{0 或‘index’,1 或‘columns’,None}},默认为 None
要插值的轴。对于 Series,此参数未使用且默认为 0。
limitint,可选
最大连续 NaN 填充数。必须大于 0。
inplacebool,默认为 False
尽可能原地更新数据。
limit_direction{{‘forward’,‘backward’,‘both’}},可选
连续的 NaN 将以此方向填充。
如果指定了限制:
-
如果‘method’为‘pad’或‘ffill’,‘limit_direction’必须为‘forward’。
-
如果‘method’为‘backfill’或‘bfill’,‘limit_direction’必须为‘backwards’。
如果未指定‘limit’:
-
如果‘method’为‘backfill’或‘bfill’,默认为‘backward’
-
否则默认为‘forward’
如果 limit_direction 为‘forward’或‘both’,则引发 ValueError
方法为‘backfill’或‘bfill’。
如果 limit_direction 为‘backward’或‘both’,则引发 ValueError
方法为‘pad’或‘ffill’。
limit_area{{None,‘inside’,‘outside’}},默认为 None
如果指定了限制,连续的 NaN 将受到此限制的影响。
-
None
:无填充限制。 -
‘inside’:仅填充被有效值包围的 NaN(插值)。
-
‘outside’:仅填充有效值之外的 NaN(外推)。
downcast可选,‘推断’或 None,默认为 None
如有可能,降低数据类型。
自版本 2.1.0 起弃用。
**kwargs
可选
传递给插值函数的关键字参数。
返回:
DataFrame 或 Series
指定频率处的插值值。
另请参阅
core.resample.Resampler.asfreq
返回新频率处的值,实质上是重新索引。
DataFrame.interpolate
使用插值方法填充 NaN 值。
注意事项
对于高频或非等间隔时间序列,重新索引后进行插值可能会导致信息丢失,如最后一个示例所示。
示例
>>> start = "2023-03-01T07:00:00"
>>> timesteps = pd.date_range(start, periods=5, freq="s")
>>> series = pd.Series(data=[1, -1, 2, 1, 3], index=timesteps)
>>> series
2023-03-01 07:00:00 1
2023-03-01 07:00:01 -1
2023-03-01 07:00:02 2
2023-03-01 07:00:03 1
2023-03-01 07:00:04 3
Freq: s, dtype: int64
通过提供周期时间为 2s,将数据框上采样到 0.5Hz。
>>> series.resample("2s").interpolate("linear")
2023-03-01 07:00:00 1
2023-03-01 07:00:02 2
2023-03-01 07:00:04 3
Freq: 2s, dtype: int64
通过提供周期时间为 500ms,将数据框降采样到 2Hz。
>>> series.resample("500ms").interpolate("linear")
2023-03-01 07:00:00.000 1.0
2023-03-01 07:00:00.500 0.0
2023-03-01 07:00:01.000 -1.0
2023-03-01 07:00:01.500 0.5
2023-03-01 07:00:02.000 2.0
2023-03-01 07:00:02.500 1.5
2023-03-01 07:00:03.000 1.0
2023-03-01 07:00:03.500 2.0
2023-03-01 07:00:04.000 3.0
Freq: 500ms, dtype: float64
在插值之前使用asfreq()
进行内部重新索引会基于重新索引的时间戳(锚点)产生插值的时间序列。由于原始系列的并非所有数据点都成为锚点,这可能导致误导性的插值结果,如下例所示:
>>> series.resample("400ms").interpolate("linear")
2023-03-01 07:00:00.000 1.0
2023-03-01 07:00:00.400 1.2
2023-03-01 07:00:00.800 1.4
2023-03-01 07:00:01.200 1.6
2023-03-01 07:00:01.600 1.8
2023-03-01 07:00:02.000 2.0
2023-03-01 07:00:02.400 2.2
2023-03-01 07:00:02.800 2.4
2023-03-01 07:00:03.200 2.6
2023-03-01 07:00:03.600 2.8
2023-03-01 07:00:04.000 3.0
Freq: 400ms, dtype: float64
注意,在两个锚点07:00:00
和07:00:02
之间,该系列错误地增加。
pandas.core.resample.Resampler.count
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.count.html
final Resampler.count()
计算组的计数,不包括缺失值。
返回:
Series 或 DataFrame
每个组内的值的计数。
另请参阅
Series.groupby
对 Series 应用 groupby 函数。
DataFrame.groupby
对 DataFrame 的每行或每列应用 groupby 函数。
示例
对于 SeriesGroupBy:
>>> lst = ['a', 'a', 'b']
>>> ser = pd.Series([1, 2, np.nan], index=lst)
>>> ser
a 1.0
a 2.0
b NaN
dtype: float64
>>> ser.groupby(level=0).count()
a 2
b 0
dtype: int64
对于 DataFrameGroupBy:
>>> data = [[1, np.nan, 3], [1, np.nan, 6], [7, 8, 9]]
>>> df = pd.DataFrame(data, columns=["a", "b", "c"],
... index=["cow", "horse", "bull"])
>>> df
a b c
cow 1 NaN 3
horse 1 NaN 6
bull 7 8.0 9
>>> df.groupby("a").count()
b c
a
1 0 2
7 1 1
对于 Resampler:
>>> ser = pd.Series([1, 2, 3, 4], index=pd.DatetimeIndex(
... ['2023-01-01', '2023-01-15', '2023-02-01', '2023-02-15']))
>>> ser
2023-01-01 1
2023-01-15 2
2023-02-01 3
2023-02-15 4
dtype: int64
>>> ser.resample('MS').count()
2023-01-01 2
2023-02-01 2
Freq: MS, dtype: int64
pandas.core.resample.Resampler.nunique
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.nunique.html
final Resampler.nunique(*args, **kwargs)
返回组中唯一元素的数量。
返回:
Series
每个组内唯一值的数量。
示例
对于 SeriesGroupby:
>>> lst = ['a', 'a', 'b', 'b']
>>> ser = pd.Series([1, 2, 3, 3], index=lst)
>>> ser
a 1
a 2
b 3
b 3
dtype: int64
>>> ser.groupby(level=0).nunique()
a 2
b 1
dtype: int64
对于 Resampler:
>>> ser = pd.Series([1, 2, 3, 3], index=pd.DatetimeIndex(
... ['2023-01-01', '2023-01-15', '2023-02-01', '2023-02-15']))
>>> ser
2023-01-01 1
2023-01-15 2
2023-02-01 3
2023-02-15 3
dtype: int64
>>> ser.resample('MS').nunique()
2023-01-01 2
2023-02-01 1
Freq: MS, dtype: int64
pandas.core.resample.Resampler.first
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.first.html
final Resampler.first(numeric_only=False, min_count=0, skipna=True, *args, **kwargs)
计算每个组内每列的第一个条目。
默认跳过 NA 元素。
参数:
numeric_only 布尔型,默认为 False
仅包括浮点数、整数、布尔值列。
min_count 整数,默认为 -1
执行操作所需的有效值数量。如果少于 min_count
个有效值,则结果将为 NA。
skipna 布尔型,默认为 True
排除 NA/null 值。如果整行/列都是 NA,则结果将为 NA。
新版本 2.2.1 中新增。
返回:
Series 或 DataFrame
每个组内的第一个值。
另请参阅
DataFrame.groupby
将函数应用于 DataFrame 的每行或每列。
pandas.core.groupby.DataFrameGroupBy.last
计算每列的最后一个非空条目。
pandas.core.groupby.DataFrameGroupBy.nth
从每个组中取出第 n 行。
示例
>>> df = pd.DataFrame(dict(A=[1, 1, 3], B=[None, 5, 6], C=[1, 2, 3],
... D=['3/11/2000', '3/12/2000', '3/13/2000']))
>>> df['D'] = pd.to_datetime(df['D'])
>>> df.groupby("A").first()
B C D
A
1 5.0 1 2000-03-11
3 6.0 3 2000-03-13
>>> df.groupby("A").first(min_count=2)
B C D
A
1 NaN 1.0 2000-03-11
3 NaN NaN NaT
>>> df.groupby("A").first(numeric_only=True)
B C
A
1 5.0 1
3 6.0 3
pandas.core.resample.Resampler.last
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.last.html
final Resampler.last(numeric_only=False, min_count=0, skipna=True, *args, **kwargs)
计算每个组内每列的最后一个条目。
默认跳过 NA 元素。
参数:
numeric_only布尔值,默认为False
仅包括浮点数、整数、布尔值列。如果为None
,将尝试使用所有内容,然后仅使用数值数据。
min_count整数,默认为-1
执行操作所需的有效值数量。如果存在少于min_count
个有效值,则结果将为 NA。
skipna布尔值,默认为True
排除 NA/null 值。如果整行/列都是 NA,则结果将为 NA。
版本 2.2.1 中的新功能。
返回:
Series 或 DataFrame
每个组内的最后值。
另请参阅
DataFrame.groupby
对 DataFrame 的每行或每列应用分组函数。
pandas.core.groupby.DataFrameGroupBy.first
计算每列的第一个非空条目。
pandas.core.groupby.DataFrameGroupBy.nth
从每个组中取第n
行。
示例
>>> df = pd.DataFrame(dict(A=[1, 1, 3], B=[5, None, 6], C=[1, 2, 3]))
>>> df.groupby("A").last()
B C
A
1 5.0 2
3 6.0 3
pandas.core.resample.Resampler.max
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.max.html
final Resampler.max(numeric_only=False, min_count=0, *args, **kwargs)
计算组的最大值。
返回:
Series 或 DataFrame
示例
>>> ser = pd.Series([1, 2, 3, 4], index=pd.DatetimeIndex(
... ['2023-01-01', '2023-01-15', '2023-02-01', '2023-02-15']))
>>> ser
2023-01-01 1
2023-01-15 2
2023-02-01 3
2023-02-15 4
dtype: int64
>>> ser.resample('MS').max()
2023-01-01 2
2023-02-01 4
Freq: MS, dtype: int64
pandas.core.resample.Resampler.mean
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.mean.html
final Resampler.mean(numeric_only=False, *args, **kwargs)
计算组的均值,不包括缺失值。
参数:
numeric_only 布尔值,默认为 False
仅包括浮点数、整数或布尔值数据。
从版本 2.0.0 开始更改:numeric_only 现在默认为 False
。
返回:
DataFrame 或 Series
每个组内数值的均值。
示例
>>> ser = pd.Series([1, 2, 3, 4], index=pd.DatetimeIndex(
... ['2023-01-01', '2023-01-15', '2023-02-01', '2023-02-15']))
>>> ser
2023-01-01 1
2023-01-15 2
2023-02-01 3
2023-02-15 4
dtype: int64
>>> ser.resample('MS').mean()
2023-01-01 1.5
2023-02-01 3.5
Freq: MS, dtype: float64
pandas.core.resample.Resampler.median
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.median.html
final Resampler.median(numeric_only=False, *args, **kwargs)
计算组的中位数,排除缺失值。
对于多重分组,结果索引将是 MultiIndex
参数:
numeric_onlybool,默认为 False
仅包括 float、int、boolean 列。
从 2.0.0 版本开始更改:numeric_only 不再接受 None
,默认为 False。
返回:
Series 或 DataFrame
每个组内的值的中位数。
示例
对于 SeriesGroupBy:
>>> lst = ['a', 'a', 'a', 'b', 'b', 'b']
>>> ser = pd.Series([7, 2, 8, 4, 3, 3], index=lst)
>>> ser
a 7
a 2
a 8
b 4
b 3
b 3
dtype: int64
>>> ser.groupby(level=0).median()
a 7.0
b 3.0
dtype: float64
对于 DataFrameGroupBy:
>>> data = {'a': [1, 3, 5, 7, 7, 8, 3], 'b': [1, 4, 8, 4, 4, 2, 1]}
>>> df = pd.DataFrame(data, index=['dog', 'dog', 'dog',
... 'mouse', 'mouse', 'mouse', 'mouse'])
>>> df
a b
dog 1 1
dog 3 4
dog 5 8
mouse 7 4
mouse 7 4
mouse 8 2
mouse 3 1
>>> df.groupby(level=0).median()
a b
dog 3.0 4.0
mouse 7.0 3.0
对于 Resampler:
>>> ser = pd.Series([1, 2, 3, 3, 4, 5],
... index=pd.DatetimeIndex(['2023-01-01',
... '2023-01-10',
... '2023-01-15',
... '2023-02-01',
... '2023-02-10',
... '2023-02-15']))
>>> ser.resample('MS').median()
2023-01-01 2.0
2023-02-01 4.0
Freq: MS, dtype: float64
pandas.core.resample.Resampler.min
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.min.html
final Resampler.min(numeric_only=False, min_count=0, *args, **kwargs)
计算分组的最小值。
返回:
Series 或 DataFrame
示例
>>> ser = pd.Series([1, 2, 3, 4], index=pd.DatetimeIndex(
... ['2023-01-01', '2023-01-15', '2023-02-01', '2023-02-15']))
>>> ser
2023-01-01 1
2023-01-15 2
2023-02-01 3
2023-02-15 4
dtype: int64
>>> ser.resample('MS').min()
2023-01-01 1
2023-02-01 3
Freq: MS, dtype: int64
pandas.core.resample.Resampler.ohlc
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.ohlc.html
final Resampler.ohlc(*args, **kwargs)
计算一组的开盘价、最高价、最低价和收盘价,排除缺失值。
对于多个分组,结果索引将是一个多索引。
返回:
DataFrame
每个组内的开盘价、最高价、最低价和收盘价。
示例
对于 SeriesGroupBy:
>>> lst = ['SPX', 'CAC', 'SPX', 'CAC', 'SPX', 'CAC', 'SPX', 'CAC',]
>>> ser = pd.Series([3.4, 9.0, 7.2, 5.2, 8.8, 9.4, 0.1, 0.5], index=lst)
>>> ser
SPX 3.4
CAC 9.0
SPX 7.2
CAC 5.2
SPX 8.8
CAC 9.4
SPX 0.1
CAC 0.5
dtype: float64
>>> ser.groupby(level=0).ohlc()
open high low close
CAC 9.0 9.4 0.5 0.5
SPX 3.4 8.8 0.1 0.1
对于 DataFrameGroupBy:
>>> data = {2022: [1.2, 2.3, 8.9, 4.5, 4.4, 3, 2 , 1],
... 2023: [3.4, 9.0, 7.2, 5.2, 8.8, 9.4, 8.2, 1.0]}
>>> df = pd.DataFrame(data, index=['SPX', 'CAC', 'SPX', 'CAC',
... 'SPX', 'CAC', 'SPX', 'CAC'])
>>> df
2022 2023
SPX 1.2 3.4
CAC 2.3 9.0
SPX 8.9 7.2
CAC 4.5 5.2
SPX 4.4 8.8
CAC 3.0 9.4
SPX 2.0 8.2
CAC 1.0 1.0
>>> df.groupby(level=0).ohlc()
2022 2023
open high low close open high low close
CAC 2.3 4.5 1.0 1.0 9.0 9.4 1.0 1.0
SPX 1.2 8.9 1.2 2.0 3.4 8.8 3.4 8.2
对于 Resampler:
>>> ser = pd.Series([1, 3, 2, 4, 3, 5],
... index=pd.DatetimeIndex(['2023-01-01',
... '2023-01-10',
... '2023-01-15',
... '2023-02-01',
... '2023-02-10',
... '2023-02-15']))
>>> ser.resample('MS').ohlc()
open high low close
2023-01-01 1 3 1 2
2023-02-01 4 5 3 5
pandas.core.resample.Resampler.prod
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.prod.html
final Resampler.prod(numeric_only=False, min_count=0, *args, **kwargs)
计算组值的乘积。
参数:
numeric_only 布尔值,默认为 False
仅包括浮点数、整数和布尔值列。
2.0.0 版本更改:numeric_only
不再接受 None
。
min_count 整数,默认为 0
执行操作所需的有效值数量。如果少于min_count
个非 NA 值存在,则结果将为 NA。
返回:
Series 或 DataFrame
计算每个组内值的乘积。
示例
>>> ser = pd.Series([1, 2, 3, 4], index=pd.DatetimeIndex(
... ['2023-01-01', '2023-01-15', '2023-02-01', '2023-02-15']))
>>> ser
2023-01-01 1
2023-01-15 2
2023-02-01 3
2023-02-15 4
dtype: int64
>>> ser.resample('MS').prod()
2023-01-01 2
2023-02-01 12
Freq: MS, dtype: int64
pandas.core.resample.Resampler.size
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.size.html
final Resampler.size()
计算分组大小。
返回:
DataFrame 或 Series
如果 as_index 为 True,则每个组中的行数作为一个 Series,如果 as_index 为 False,则作为一个 DataFrame。
另请参阅
Series.groupby
对 Series 应用 groupby 函数。
DataFrame.groupby
对 DataFrame 的每一行或每一列应用函数 groupby。
示例
对于 SeriesGroupBy:
>>> lst = ['a', 'a', 'b']
>>> ser = pd.Series([1, 2, 3], index=lst)
>>> ser
a 1
a 2
b 3
dtype: int64
>>> ser.groupby(level=0).size()
a 2
b 1
dtype: int64
>>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]]
>>> df = pd.DataFrame(data, columns=["a", "b", "c"],
... index=["owl", "toucan", "eagle"])
>>> df
a b c
owl 1 2 3
toucan 1 5 6
eagle 7 8 9
>>> df.groupby("a").size()
a
1 2
7 1
dtype: int64
对于 Resampler:
>>> ser = pd.Series([1, 2, 3], index=pd.DatetimeIndex(
... ['2023-01-01', '2023-01-15', '2023-02-01']))
>>> ser
2023-01-01 1
2023-01-15 2
2023-02-01 3
dtype: int64
>>> ser.resample('MS').size()
2023-01-01 2
2023-02-01 1
Freq: MS, dtype: int64
pandas.core.resample.Resampler.sem
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.sem.html
final Resampler.sem(ddof=1, numeric_only=False, *args, **kwargs)
计算组的均值标准误差,排除缺失值。
对于多个分组,结果索引将是一个 MultiIndex。
参数:
ddofint,默认值为 1
自由度。
numeric_onlybool,默认值为 False
仅包括浮点数、整数或布尔值数据。
于版本 1.5.0 中新增。
在版本 2.0.0 中更改:numeric_only 现在默认为 False
。
返回:
Series 或 DataFrame
每个组内值的均值标准误差。
示例
对于 SeriesGroupBy:
>>> lst = ['a', 'a', 'b', 'b']
>>> ser = pd.Series([5, 10, 8, 14], index=lst)
>>> ser
a 5
a 10
b 8
b 14
dtype: int64
>>> ser.groupby(level=0).sem()
a 2.5
b 3.0
dtype: float64
对于 DataFrameGroupBy:
>>> data = [[1, 12, 11], [1, 15, 2], [2, 5, 8], [2, 6, 12]]
>>> df = pd.DataFrame(data, columns=["a", "b", "c"],
... index=["tuna", "salmon", "catfish", "goldfish"])
>>> df
a b c
tuna 1 12 11
salmon 1 15 2
catfish 2 5 8
goldfish 2 6 12
>>> df.groupby("a").sem()
b c
a
1 1.5 4.5
2 0.5 2.0
对于 Resampler:
>>> ser = pd.Series([1, 3, 2, 4, 3, 8],
... index=pd.DatetimeIndex(['2023-01-01',
... '2023-01-10',
... '2023-01-15',
... '2023-02-01',
... '2023-02-10',
... '2023-02-15']))
>>> ser.resample('MS').sem()
2023-01-01 0.577350
2023-02-01 1.527525
Freq: MS, dtype: float64
pandas.core.resample.Resampler.std
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.std.html
final Resampler.std(ddof=1, numeric_only=False, *args, **kwargs)
计算组的标准差,不包括缺失值。
参数:
ddof整数,默认为 1。
自由度。
numeric_only布尔值,默认为 False。
仅包括浮点数、整数或布尔值数据。
新版本 1.5.0 中新增。
在版本 2.0.0 中更改:numeric_only 现在默认为 False
。
返回:
DataFrame 或 Series
每个组内数值的标准差。
示例
>>> ser = pd.Series([1, 3, 2, 4, 3, 8],
... index=pd.DatetimeIndex(['2023-01-01',
... '2023-01-10',
... '2023-01-15',
... '2023-02-01',
... '2023-02-10',
... '2023-02-15']))
>>> ser.resample('MS').std()
2023-01-01 1.000000
2023-02-01 2.645751
Freq: MS, dtype: float64
pandas.core.resample.Resampler.sum
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.sum.html
final Resampler.sum(numeric_only=False, min_count=0, *args, **kwargs)
计算组值的总和。
参数:
numeric_onlybool,默认值为 False
仅包括浮点数、整数和布尔值列。
在 2.0.0 版本中更改:numeric_only 不再接受None
。
min_countint,默认值为 0
执行操作所需的有效值的数量。如果少于min_count
个非 NA 值存在,则结果将为 NA。
返回:
Series 或 DataFrame
计算每个组内值的总和。
示例
>>> ser = pd.Series([1, 2, 3, 4], index=pd.DatetimeIndex(
... ['2023-01-01', '2023-01-15', '2023-02-01', '2023-02-15']))
>>> ser
2023-01-01 1
2023-01-15 2
2023-02-01 3
2023-02-15 4
dtype: int64
>>> ser.resample('MS').sum()
2023-01-01 3
2023-02-01 7
Freq: MS, dtype: int64
pandas.core.resample.Resampler.var
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.var.html
final Resampler.var(ddof=1, numeric_only=False, *args, **kwargs)
计算组的方差,不包括缺失值。
参数:
ddofint,默认为 1
自由度。
numeric_onlybool,默认为 False
仅包括浮点数、整数或布尔值数据。
自 1.5.0 版本起新增。
在 2.0.0 版本中更改:numeric_only 现在默认为False
。
返回:
DataFrame 或 Series
每个组内数值的方差。
示例
>>> ser = pd.Series([1, 3, 2, 4, 3, 8],
... index=pd.DatetimeIndex(['2023-01-01',
... '2023-01-10',
... '2023-01-15',
... '2023-02-01',
... '2023-02-10',
... '2023-02-15']))
>>> ser.resample('MS').var()
2023-01-01 1.0
2023-02-01 7.0
Freq: MS, dtype: float64
>>> ser.resample('MS').var(ddof=0)
2023-01-01 0.666667
2023-02-01 4.666667
Freq: MS, dtype: float64
pandas.core.resample.Resampler.quantile
原文:
pandas.pydata.org/docs/reference/api/pandas.core.resample.Resampler.quantile.html
final Resampler.quantile(q=0.5, **kwargs)
返回给定分位数处的值。
参数:
qfloat 或类似数组,默认为 0.5(50%分位数)
返回:
DataFrame 或 Series
每个组内值的分位数。
另请参阅
Series.quantile
返回一个系列,其中索引是 q,值是分位数。
DataFrame.quantile
返回一个 DataFrame,其中列是 self 的列,值是分位数。
DataFrameGroupBy.quantile
返回一个 DataFrame,其中列是 groupby 列,值是其分位数。
示例
>>> ser = pd.Series([1, 3, 2, 4, 3, 8],
... index=pd.DatetimeIndex(['2023-01-01',
... '2023-01-10',
... '2023-01-15',
... '2023-02-01',
... '2023-02-10',
... '2023-02-15']))
>>> ser.resample('MS').quantile()
2023-01-01 2.0
2023-02-01 4.0
Freq: MS, dtype: float64
>>> ser.resample('MS').quantile(.25)
2023-01-01 1.5
2023-02-01 3.5
Freq: MS, dtype: float64
样式
Styler
对象由 pandas.DataFrame.style
返回。
Styler 构造函数
Styler (data[, precision, table_styles, ...]) |
根据数据使用 HTML 和 CSS 为 DataFrame 或 Series 添加样式。 |
---|---|
Styler.from_custom_template (searchpath[, ...]) |
用于创建 Styler 子类的工厂函数。 |
Styler 属性
Styler.env |
|
---|---|
Styler.template_html |
|
Styler.template_html_style |
|
Styler.template_html_table |
|
Styler.template_latex |
|
Styler.template_string |
|
Styler.loader |
样式应用
Styler.apply (func[, axis, subset]) |
对列、行或整个表格应用 CSS 样式函数。 |
---|---|
Styler.map (func[, subset]) |
对每个元素应用 CSS 样式函数。 |
Styler.apply_index (func[, axis, level]) |
对索引或列标题逐级应用 CSS 样式函数。 |
Styler.map_index |
将 CSS 样式函数应用于索引或列标题,逐个元素。 |
Styler.format ([formatter, subset, na_rep, ...]) |
格式化单元格的文本显示值。 |
Styler.format_index ([formatter, axis, ...]) |
格式化索引标签或列标题的文本显示值。 |
Styler.relabel_index (labels[, axis, level]) |
重新标签化索引或列标题键,以显示一组指定的值。 |
Styler.hide ([subset, axis, level, names]) |
隐藏整个索引 / 列标题,或者从显示中隐藏特定行 / 列。 |
Styler.concat (other) |
将另一个 Styler 追加到一起,将输出合并成一个表格。 |
Styler.set_td_classes (classes) |
设置 <td> HTML 元素的 class 属性。 |
Styler.set_table_styles ([table_styles, ...]) |
设置包含在 <style> HTML 元素中的表格样式。 |
Styler.set_table_attributes (attributes) |
设置添加到 <table> HTML 元素的表格属性。 |
Styler.set_tooltips (ttips[, props, css_class]) |
在 Styler 上设置生成 :hover 工具提示的字符串 DataFrame。 |
Styler.set_caption (caption) |
设置添加到 <caption> HTML 元素的文本。 |
Styler.set_sticky ([axis, pixel_size, levels]) |
添加 CSS 以永久显示索引或列标题在滚动框架中。 |
Styler.set_properties ([subset]) |
为给定子集的每个 <td> HTML 元素设置定义的 CSS 属性。 |
Styler.set_uuid (uuid) |
设置应用于 HTML 元素的 id 属性的 uuid。 |
Styler.clear () |
重置 Styler ,移除任何先前应用的样式。 |
Styler.pipe (func, *args, **kwargs) |
应用 func(self, *args, **kwargs) ,并返回结果。 |
内置样式
Styler.highlight_null ([color, subset, props]) |
用样式突出显示缺失值。 |
---|---|
Styler.highlight_max ([subset, color, axis, ...]) |
用样式突出显示最大值。 |
Styler.highlight_min ([subset, color, axis, ...]) |
用样式突出显示最小值。 |
Styler.highlight_between ([subset, color, ...]) |
用样式突出显示定义的范围。 |
Styler.highlight_quantile ([subset, color, ...]) |
用样式突出显示由分位数定义的值。 |
Styler.background_gradient ([cmap, low, ...]) |
以渐变样式着色背景。 |
Styler.text_gradient ([cmap, low, high, ...]) |
以渐变样式着色文本。 |
Styler.bar ([subset, axis, color, cmap, ...]) |
在单元格背景中绘制条形图。 |
样式导出和导入
Styler.to_html ([buf, table_uuid, ...]) |
将 Styler 写入文件、缓冲区或字符串,格式为 HTML-CSS。 |
---|---|
Styler.to_latex ([buf, column_format, ...]) |
将 Styler 写入文件、缓冲区或字符串,格式为 LaTeX。 |
Styler.to_excel (excel_writer[, sheet_name, ...]) |
将 Styler 写入 Excel 表格。 |
Styler.to_string ([buf, encoding, ...]) |
将 Styler 写入文件、缓冲区或字符串,格式为文本。 |
Styler.export () |
导出应用于当前 Styler 的样式。 |
Styler.use (styles) |
在当前 Styler 上设置样式。 |
Styler 构造函数
Styler (data[, precision, table_styles, ...]) |
根据数据为 DataFrame 或 Series 提供 HTML 和 CSS 样式。 |
---|---|
Styler.from_custom_template (searchpath[, ...]) |
创建 Styler 的子类的工厂函数。 |
Styler 属性
Styler.env |
|
---|---|
Styler.template_html |
|
Styler.template_html_style |
|
Styler.template_html_table |
|
Styler.template_latex |
|
Styler.template_string |
|
Styler.loader |
样式应用
Styler.apply (func[, axis, subset]) |
逐列、逐行或整个表格应用 CSS 样式函数。 |
---|---|
Styler.map (func[, subset]) |
逐元素应用 CSS 样式函数。 |
Styler.apply_index (func[, axis, level]) |
逐级别地将 CSS 样式函数应用于索引或列标题。 |
Styler.map_index (func[, axis, level]) |
逐元素地将 CSS 样式函数应用于索引或列标题。 |
Styler.format ([formatter, subset, na_rep, ...]) |
格式化单元格的文本显示值。 |
Styler.format_index ([formatter, axis, ...]) |
格式化索引标签或列标题的文本显示值。 |
Styler.relabel_index (labels[, axis, level]) |
重新标记索引或列标题键,以显示一组指定的值。 |
Styler.hide ([subset, axis, level, names]) |
隐藏整个索引/列标题,或者从显示中隐藏特定行/列。 |
Styler.concat (other) |
将另一个 Styler 追加到一起,将输出合并为单个表格。 |
Styler.set_td_classes (classes) |
设置<td> HTML 元素的class 属性。 |
Styler.set_table_styles ([table_styles, ...]) |
设置包含在 <style> HTML 元素中的表样式。 |
Styler.set_table_attributes (attributes) |
设置添加到 <table> HTML 元素中的表属性。 |
Styler.set_tooltips (ttips[, props, css_class]) |
在 Styler 上设置生成 :hover 工具提示的字符串 DataFrame。 |
Styler.set_caption (caption) |
设置添加到 <caption> HTML 元素中的文本。 |
Styler.set_sticky ([axis, pixel_size, levels]) |
向永久显示索引或列标题的滚动框架添加 CSS。 |
Styler.set_properties ([subset]) |
为给定的子集设置每个 <td> HTML 元素的定义的 CSS 属性。 |
Styler.set_uuid (uuid) |
设置应用于 HTML 元素的 id 属性的 uuid。 |
Styler.clear () |
重置 Styler ,移除任何先前应用的样式。 |
Styler.pipe (func, *args, **kwargs) |
应用 func(self, *args, **kwargs) ,并返回结果。 |
内建样式
Styler.highlight_null ([color, subset, props]) |
使用样式突出显示缺失值。 |
---|---|
Styler.highlight_max ([subset, color, axis, ...]) |
使用样式突出显示最大值。 |
Styler.highlight_min ([subset, color, axis, ...]) |
使用样式突出显示最小值。 |
Styler.highlight_between ([subset, color, ...]) |
使用样式突出显示定义范围内的内容。 |
Styler.highlight_quantile ([subset, color, ...]) |
使用样式突出显示由分位数定义的值。 |
Styler.background_gradient ([cmap, low, ...]) |
以渐变样式着色背景。 |
Styler.text_gradient ([cmap, low, high, ...]) |
以渐变样式着色文本。 |
Styler.bar ([subset, axis, color, cmap, ...]) |
在单元格背景中绘制条形图。 |
样式导出和导入
Styler.to_html ([buf, table_uuid, ...]) |
将 Styler 写入 HTML-CSS 格式的文件、缓冲区或字符串。 |
---|---|
Styler.to_latex ([buf, column_format, ...]) |
将 Styler 写入 LaTeX 格式的文件、缓冲区或字符串。 |
Styler.to_excel (excel_writer[, sheet_name, ...]) |
将 Styler 写入 Excel 表格。 |
Styler.to_string ([buf, encoding, ...]) |
将 Styler 写入文本格式的文件、缓冲区或字符串。 |
Styler.export () |
导出应用于当前 Styler 的样式。 |
Styler.use (styles) |
在当前 Styler 上设置样式。 |
pandas.io.formats.style.Styler
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.html
class pandas.io.formats.style.Styler(data, precision=None, table_styles=None, uuid=None, caption=None, table_attributes=None, cell_ids=True, na_rep=None, uuid_len=5, decimal=None, thousands=None, escape=None, formatter=None)
用 HTML 和 CSS 样式化 DataFrame 或 Series 数据。
参数:
dataSeries 或 DataFrame
要样式化的数据 - 可以是 Series 或 DataFrame。
precisionint,可选
浮点数舍入精度。如果未给出,则默认为 pandas.options.styler.format.precision
。
在版本 1.4.0 中更改。
table_styles类似列表,默认为 None
{选择器: (属性, 值)} 字典列表;请参阅注意事项。
uuidstr,默认为 None
用于避免 CSS 冲突的唯一标识符;自动生成。
captionstr,元组,默认为 None
要附加到表格的字符串标题。元组仅用于 LaTeX 双标题。
table_attributesstr,默认为 None
除自动生成(默认)的 id 外,出现在开头的 <table>
标签中的项目。
cell_idsbool,默认为 True
如果为 True,则每个单元格都将在其 HTML 标签中具有一个 id
属性。id
的形式为 T_<uuid>_row<num_row>_col<num_col>
,其中 <uuid>
是唯一标识符,<num_row>
是行号,<num_col>
是列号。
na_repstr,可选
用于缺失值的表示。如果 na_rep
为 None,则不应用特殊格式,并回退到 pandas.options.styler.format.na_rep
。
uuid_lenint,默认为 5
如果未指定 uuid
,则要随机生成的 uuid
的长度表示为十六进制字符,在范围 [0, 32] 中。
decimalstr,可选
用于浮点数、复数和整数的小数分隔符。如果未给出,则使用 pandas.options.styler.format.decimal
。
在版本 1.3.0 中新增。
thousandsstr,可选,默认为 None
用于浮点数、复数和整数的千位分隔符。如果未给出,则使用 pandas.options.styler.format.thousands
。
在版本 1.3.0 中新增。
escapestr,可选
使用 'html' 将单元格显示字符串中的字符 &
、<
、>
、'
和 "
替换为 HTML 安全序列。使用 'latex' 将单元格显示字符串中的字符 &
、%
、$
、#
、_
、{
、}
、~
、^
和 \
替换为 LaTeX 安全序列。使用 'latex-math' 将字符替换为与 'latex' 模式相同的方式,除了数学子字符串,它要么被两个字符 $
包围,要么以字符 \(
开头,以 \)
结束。如果未给出,则使用 pandas.options.styler.format.escape
。
在版本 1.3.0 中新增。
formatterstr、callable、dict,可选
用于定义值的显示方式。参见 Styler.format
。如果未给出,则使用 pandas.options.styler.format.formatter
。
在版本 1.4.0 中新增。
另请参阅
DataFrame.style
返回一个 Styler 对象,其中包含用于为 DataFrame 构建样式化 HTML 表示的方法。
注意事项
大多数样式都可以通过将样式函数传递给 Styler.apply
或 Styler.map
来完成。样式函数应返回包含 CSS 'attr: value'
的字符串,这将应用于指定的单元格。
如果在 Jupyter 笔记本中使用,Styler 已定义了 _repr_html_
来自动渲染自身。否则,调用 Styler.to_html
来获取生成的 HTML。
生成的 HTML 上附加了 CSS 类。
-
索引和列名包括
index_name
和level<k>
其中 k 是其在 MultiIndex 中的级别 -
索引标签单元格包括
-
row_heading
-
row<n>
其中 n 是行的数字位置 -
level<k>
其中 k 是 MultiIndex 中的级别
-
-
列标签单元格包括*
col_heading
*col<n>
,其中 n 是列的数字位置 *level<k>
其中 k 是 MultiIndex 中的级别 -
空单元格包括
blank
-
数据单元格包括
data
-
去除了
col_trim
或row_trim
的单元格。
通过在 Styler.set_table_classes
中使用 css_class_names
参数,可以重新命名这些类中的任何一个,或全部,例如{“row”: “MY_ROW_CLASS”, “col_trim”: “”, “row_trim”: “”}。
示例
>>> df = pd.DataFrame([[1.0, 2.0, 3.0], [4, 5, 6]], index=['a', 'b'],
... columns=['A', 'B', 'C'])
>>> pd.io.formats.style.Styler(df, precision=2,
... caption="My table")
请参见:表可视化 获取更多示例。
属性
env | (Jinja2 jinja2.Environment) |
---|---|
template_html | (Jinja2 模板) |
template_html_table | (Jinja2 模板) |
template_html_style | (Jinja2 模板) |
template_latex | (Jinja2 模板) |
loader | (Jinja2 Loader) |
属性
env |
|
---|---|
loader |
|
template_html |
|
template_html_style |
|
template_html_table |
|
template_latex |
|
template_string |
方法
apply (func[, axis, subset]) |
对列、行或整个表应用 CSS 样式函数。 |
---|---|
apply_index |
逐层为索引或列标题应用 CSS 样式函数。 |
applymap (func) |
(已弃用)逐个元素应用 CSS 样式函数。 |
applymap_index (func) |
(已弃用)逐个元素为索引或列标题应用 CSS 样式函数。 |
background_gradient |
以渐变样式着色背景。 |
bar |
在单元格背景中绘制条形图。 |
clear |
重置Styler ,移除任何先前应用的样式。 |
concat |
将另一个 Styler 追加到一起,将输出合并为单个表格。 |
export |
导出应用于当前 Styler 的样式。 |
format |
格式化单元格的文本显示值。 |
format_index |
格式化索引标签或列标题的文本显示值。 |
from_custom_template |
创建Styler 子类的工厂函数。 |
hide |
隐藏整个索引/列标题,或从显示中隐藏特定行/列。 |
highlight_between |
使用样式突出显示定义的范围。 |
highlight_max ([subset, color, axis, props]) |
使用样式突出显示最大值。 |
highlight_min ([subset, color, axis, props]) |
使用样式突出显示最小值。 |
highlight_null ([color, subset, props]) |
使用样式突出显示缺失值。 |
highlight_quantile ([subset, color, axis, ...]) |
使用样式突出显示由分位数定义的值。 |
map (func[, subset]) |
按元素方式应用 CSS 样式函数。 |
map_index (func[, axis, level]) |
将 CSS 样式函数应用于索引或列标题,按元素方式处理。 |
pipe (func, *args, **kwargs) |
应用 func(self, *args, **kwargs) ,并返回结果。 |
relabel_index (labels[, axis, level]) |
重新标记索引或列标题的键,以显示一组指定的值。 |
set_caption (caption) |
设置添加到 <caption> HTML 元素的文本。 |
set_properties ([subset]) |
为给定子集的每个 <td> HTML 元素设置定义的 CSS 属性。 |
set_sticky ([axis, pixel_size, levels]) |
添加 CSS 以永久性地在滚动帧中显示索引或列标题。 |
set_table_attributes (attributes) |
设置添加到 <table> HTML 元素的表属性。 |
set_table_styles ([table_styles, axis, ...]) |
设置包含在<style> HTML 元素中的表样式。 |
set_td_classes (classes) |
设置<td> HTML 元素的class 属性。 |
set_tooltips (ttips[, props, css_class]) |
在生成Styler 的:hover 工具提示时设置字符串的 DataFrame。 |
set_uuid (uuid) |
设置应用于 HTML 元素的id 属性的 uuid。 |
text_gradient ([cmap, low, high, axis, ...]) |
以渐变样式着色文本。 |
to_excel (excel_writer[, sheet_name, na_rep, ...]) |
将 Styler 写入 Excel 表。 |
to_html ([buf, table_uuid, table_attributes, ...]) |
将 Styler 写入文件,缓冲区或 HTML-CSS 格式的字符串。 |
to_latex ([buf, column_format, position, ...]) |
将 Styler 写入文件,缓冲区或 LaTeX 格式的字符串。 |
to_string ([buf, encoding, sparse_index, ...]) |
将 Styler 写入文件,缓冲区或文本格式的字符串。 |
use (styles) |
设置当前 Styler 的样式。 |
pandas.io.formats.style.Styler.from_custom_template
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.from_custom_template.html
classmethod Styler.from_custom_template(searchpath, html_table=None, html_style=None)
用于创建 Styler
的子类的工厂函数。
使用自定义模板和 Jinja 环境。
在版本 1.3.0 中更改。
参数:
searchpath 字符串或列表
包含模板的目录的路径或路径。
html_table 字符串
自定义模板的名称,用于替换 html_table 模板。
新功能在版本 1.3.0 中引入。
html_style 字符串
自定义模板的名称,用于替换 html_style 模板。
新功能在版本 1.3.0 中引入。
返回:
MyStyler Styler 的子类
具有正确的 env
、template_html
、template_html_table
和 template_html_style
类属性设置。
示例
>>> from pandas.io.formats.style import Styler
>>> EasyStyler = Styler.from_custom_template("path/to/template",
... "template.tpl",
... )
>>> df = pd.DataFrame({"A": [1, 2]})
>>> EasyStyler(df)
请参阅:表格可视化 以获取更多示例。
pandas.io.formats.style.Styler.env
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.env.html
Styler.env = <jinja2.environment.Environment object>
pandas.io.formats.style.Styler.template_html
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.template_html.html
Styler.template_html = <Template 'html.tpl'>
pandas.io.formats.style.Styler.template_html_style
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.template_html_style.html
Styler.template_html_style = <Template 'html_style.tpl'>
pandas.io.formats.style.Styler.template_html_table
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.template_html_table.html
Styler.template_html_table = <Template 'html_table.tpl'>
pandas.io.formats.style.Styler.template_latex
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.template_latex.html
Styler.template_latex = <Template 'latex.tpl'>
pandas.io.formats.style.Styler.template_string
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.template_string.html
Styler.template_string = <Template 'string.tpl'>
pandas.io.formats.style.Styler.loader
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.loader.html
Styler.loader = <jinja2.loaders.PackageLoader object>
pandas.io.formats.style.Styler.apply
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.apply.html
Styler.apply(func, axis=0, subset=None, **kwargs)
对列、行或整个表格逐列应用 CSS 样式函数。
更新 HTML 表示以显示结果。
参数:
func函数
如果axis
在 [0,1] 中,func
应该接受一个 Series,并返回相同长度的类似列表对象,或者一个 Series,不一定是相同长度的,考虑到subset
的有效索引标签。如果axis
是None
,func
应该接受一个 DataFrame,并返回形状相同的 ndarray 或 DataFrame,不一定是相同形状的,考虑到subset
的有效索引和列标签。
版本 1.3.0 中的更改。
版本 1.4.0 中的更改。
axis,默认 0
对每列应用(axis=0
或'index'
),对每行应用(axis=1
或'columns'
),或者一次对整个 DataFrame 应用(axis=None
)。
subset标签,类似数组,IndexSlice,可选
一个有效的 2D 输入到 DataFrame.loc[data
。
****kwargs**dict
传递给func
。
返回:
Styler
另请参见
Styler.map_index
对标题元素逐个应用 CSS 样式函数。
Styler.apply_index
对标题级别逐级应用 CSS 样式函数。
Styler.map
逐个应用 CSS 样式函数。
注意
func
的输出元素应该是 CSS 样式字符串,格式为‘attribute: value; attribute2: value2; …’,或者如果不应用任何内容到该元素,则为空字符串或None
。
这类似于DataFrame.apply
,不同之处在于axis=None
一次将函数应用于整个 DataFrame,而不是逐列或逐行。
示例
>>> def highlight_max(x, color):
... return np.where(x == np.nanmax(x.to_numpy()), f"color: {color};", None)
>>> df = pd.DataFrame(np.random.randn(5, 2), columns=["A", "B"])
>>> df.style.apply(highlight_max, color='red')
>>> df.style.apply(highlight_max, color='blue', axis=1)
>>> df.style.apply(highlight_max, color='green', axis=None)
使用subset
来限制应用到单个列或多个列
>>> df.style.apply(highlight_max, color='red', subset="A")
...
>>> df.style.apply(highlight_max, color='red', subset=["A", "B"])
...
使用 2D 输入到subset
以选择行以及列
>>> df.style.apply(highlight_max, color='red', subset=([0, 1, 2], slice(None)))
...
>>> df.style.apply(highlight_max, color='red', subset=(slice(0, 5, 2), "A"))
...
使用返回包含有效索引标签但长度不等的 Series / DataFrame 的函数
>>> df = pd.DataFrame([[1, 2], [3, 4], [4, 6]], index=["A1", "A2", "Total"])
>>> total_style = pd.Series("font-weight: bold;", index=["Total"])
>>> df.style.apply(lambda s: total_style)
有关更多详细信息,请参阅表可视化用户指南。
pandas.io.formats.style.Styler.map
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.map.html
Styler.map(func, subset=None, **kwargs)
逐元素应用 CSS 样式函数。
更新 HTML 表示以显示结果。
参数:
func 函数
func
应该接受标量并返回字符串。
subset 标签,类数组,IndexSlice,可选
对于 DataFrame.loc[data
限制为 之前 的部分。
**kwargs 字典
传递给 func
。
返回:
Styler
另请参见
逐个元素应用 CSS 样式函数到表头。
逐层应用 CSS 样式函数到表头。
逐列、逐行或逐表应用 CSS 样式函数。
注意事项
func
的输出元素应为 CSS 样式字符串,格式为 ‘attribute: value; attribute2: value2; …’,或者,如果要应用于该元素,则为空字符串或 None
。
示例
>>> def color_negative(v, color):
... return f"color: {color};" if v < 0 else None
>>> df = pd.DataFrame(np.random.randn(5, 2), columns=["A", "B"])
>>> df.style.map(color_negative, color='red')
使用 subset
限制仅应用于单列或多列
>>> df.style.map(color_negative, color='red', subset="A")
...
>>> df.style.map(color_negative, color='red', subset=["A", "B"])
...
使用 2 维输入到 subset
以选择行以及列
>>> df.style.map(color_negative, color='red',
... subset=([0,1,2], slice(None)))
>>> df.style.map(color_negative, color='red', subset=(slice(0,5,2), "A"))
...
有关更多详细信息,请参见表可视化用户指南。
pandas.io.formats.style.Styler.apply_index
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.apply_index.html
Styler.apply_index(func, axis=0, level=None, **kwargs)
对索引或列标题按级别应用 CSS 样式函数。
使用结果更新 HTML 表示。
从 1.4.0 版本开始。
从 2.1.0 版本开始:Styler.applymap_index
已被弃用并更名为Styler.map_index
。
参数:
func函数
func
应该接受一个 Series 并返回一个相同长度的字符串数组。
axis
应用函数的标头。
level整数,字符串,列表,可选的
如果索引是 MultiIndex,则应用函数的级别。
****kwargs**字典
传递给func
。
返回:
Styler
另请参阅
Styler.map_index
对标头逐个元素应用 CSS 样式函数。
Styler.apply
对列、行或整个表格应用 CSS 样式函数。
Styler.map
逐个元素应用 CSS 样式函数。
注意事项
func
的每个输入将作为 Series 的索引,如果是索引,则为 MultiIndex 的级别。func
的输出应该是相同大小的字符串数组,格式为“属性:值;属性 2:值 2;…”或,如果不想应用于该元素,则为空字符串或None
。
示例
在索引中有条件地突出显示值的基本用法。
>>> df = pd.DataFrame([[1,2], [3,4]], index=["A", "B"])
>>> def color_b(s):
... return np.where(s == "B", "background-color: yellow;", "")
>>> df.style.apply_index(color_b)
选择性地应用于 MultiIndex 列的特定级别。
>>> midx = pd.MultiIndex.from_product([['ix', 'jy'], [0, 1], ['x3', 'z4']])
>>> df = pd.DataFrame([np.arange(8)], columns=midx)
>>> def highlight_x(s):
... return ["background-color: yellow;" if "x" in v else "" for v in s]
>>> df.style.apply_index(highlight_x, axis="columns", level=[0, 2])
...
pandas.io.formats.style.Styler.map_index
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.map_index.html
Styler.map_index(func, axis=0, level=None, **kwargs)
将 CSS 样式函数应用于索引或列标题,逐元素。
使用结果更新 HTML 表示。
新版本 1.4.0 中。
新版本 2.1.0 中:Styler.applymap_index 已被弃用,并更名为 Styler.map_index。
参数:
funcfunction
func
应该接受一个标量并返回一个字符串。
axis
应用函数的标题。
levelint, str, list, optional
如果索引是多重索引,则应用函数的级别。
****kwargs**dict
传递给 func
。
返回:
Styler
另请参阅
Styler.apply_index
逐级别应用 CSS 样式函数于标题。
Styler.apply
逐列、逐行或整个表格应用 CSS 样式函数。
Styler.map
逐元素应用 CSS 样式函数。
注释
func
的每个输入将是一个索引值(如果是索引)或多重索引的级别值。func
的输出应该是 CSS 样式字符串,格式为 ‘attribute: value; attribute2: value2; …’,或者,如果不应用于该元素,则为空字符串或 None
。
示例
在索引中有条件地突出显示值的基本用法。
>>> df = pd.DataFrame([[1,2], [3,4]], index=["A", "B"])
>>> def color_b(s):
... return "background-color: yellow;" if v == "B" else None
>>> df.style.map_index(color_b)
有选择地应用于多重索引列的特定级别。
>>> midx = pd.MultiIndex.from_product([['ix', 'jy'], [0, 1], ['x3', 'z4']])
>>> df = pd.DataFrame([np.arange(8)], columns=midx)
>>> def highlight_x(v):
... return "background-color: yellow;" if "x" in v else None
>>> df.style.map_index(highlight_x, axis="columns", level=[0, 2])
...
pandas.io.formats.style.Styler.format
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.format.html
Styler.format(formatter=None, subset=None, na_rep=None, precision=None, decimal='.', thousands=None, escape=None, hyperlinks=None)
格式化单元格的文本显示值。
参数:
formatter字符串,可调用,字典或 None
用于定义值如何显示的对象。请参阅注释。
subset标签,类似数组,IndexSlice,可选
有效的 2D 输入用于 DataFrame.loc[data
在应用函数之前的范围。
na_rep字符串,可选
用于缺失值的表示。如果na_rep
为 None,则不应用任何特殊格式。
precision整数,可选
用于显示目的的浮点精度,如果未由指定的formatter
确定。
自版本 1.3.0 起新增。
decimal字符串,默认为“.”
用作浮点数、复数和整数的小数点分隔符的字符。
自版本 1.3.0 起新增。
thousands字符串,可选,默认为 None
用作浮点数、复数和整数的千位分隔符的字符。
自版本 1.3.0 起新增。
escape字符串,可选
使用‘html’将单元格显示字符串中的字符&
,<
,>
,'
和"
替换为 HTML 安全序列。使用‘latex’将单元格显示字符串中的字符&
,%
,$
,#
,_
,{
,}
,~
,^
和\
替换为 LaTeX 安全序列。使用‘latex-math’以与‘latex’模式相同的方式替换字符,除了数学子字符串,这些子字符串要么被两个字符$
包围,要么以字符\(
开头,以\)
结尾。转义在formatter
之前完成。
自版本 1.3.0 起新增。
超链接,可选
将包含https://、http://、ftp://或 www.的字符串模式转换为 HTML 标签,作为可点击的 URL 超链接,如果是“html”,或者转换为 LaTeX href 命令,如果是“latex”。
自版本 1.4.0 起新增。
返回:
样式化器
另请参阅
Styler.format_index
格式化索引标签的文本显示值。
注释
此方法为 DataFrame 中的每个单元格分配一个格式化函数formatter
。如果formatter
为None
,则使用默认格式化程序。如果是可调用的,则该函数应将数据值作为输入并返回可显示的表示,例如字符串。如果formatter
给定为字符串,则假定为有效的 Python 格式规范,并将其包装为可调用的string.format(x)
。如果给定一个dict
,键应对应列名,值应为字符串或可调用对象,如上所述。
默认格式化程序当前使用 pandas 显示精度表示浮点数和复数,除非在此处使用precision
参数。默认格式化程序不会调整缺失值的表示,除非使用na_rep
参数。
subset
参数定义要应用格式化函数的区域。如果以字典形式给出的formatter
参数不包括子集中的所有列,则这些列将应用默认的 formatter。在 formatter 字典中排除在子集之外的任何列将被忽略。
当使用formatter
字符串时,数据类型必须兼容,否则将引发 ValueError。
在实例化 Styler 时,可以通过设置pandas.options
来应用默认格式:
styler.format.formatter
:默认为 None。styler.format.na_rep
:默认为 None。styler.format.precision
:默认为 6。styler.format.decimal
:默认为“.”。styler.format.thousands
:默认为 None。styler.format.escape
:默认为 None。
警告
当使用输出格式Styler.to_excel
时,Styler.format
将被忽略,因为 Excel 和 Python 具有不同的格式结构。但是,可以使用数字格式伪 CSS 属性来强制 Excel 允许的格式。请参见示例。
示例
使用默认的formatter
来使用na_rep
和precision
>>> df = pd.DataFrame([[np.nan, 1.0, 'A'], [2.0, np.nan, 3.0]])
>>> df.style.format(na_rep='MISS', precision=3)
0 1 2
0 MISS 1.000 A
1 2.000 MISS 3.000
在一致的列数据类型上使用formatter
规范
>>> df.style.format('{:.2f}', na_rep='MISS', subset=[0,1])
0 1 2
0 MISS 1.00 A
1 2.00 MISS 3.000000
对于未指定列使用默认的formatter
>>> df.style.format({0: '{:.2f}', 1: '£ {:.1f}'}, na_rep='MISS', precision=1)
...
0 1 2
0 MISS £ 1.0 A
1 2.00 MISS 3.0
在默认的formatter
下使用多个na_rep
或precision
规范。
>>> (df.style.format(na_rep='MISS', precision=1, subset=[0])
... .format(na_rep='PASS', precision=2, subset=[1, 2]))
0 1 2
0 MISS 1.00 A
1 2.0 PASS 3.00
使用可调用的formatter
函数。
>>> func = lambda s: 'STRING' if isinstance(s, str) else 'FLOAT'
>>> df.style.format({0: '{:.1f}', 2: func}, precision=4, na_rep='MISS')
...
0 1 2
0 MISS 1.0000 STRING
1 2.0 MISS FLOAT
使用带有 HTML escape
和na_rep
的formatter
。
>>> df = pd.DataFrame([['<div></div>', '"A&B"', None]])
>>> s = df.style.format(
... '<a href="a.com/{0}">{0}</a>', escape="html", na_rep="NA"
... )
>>> s.to_html()
...
<td .. ><a href="a.com/<div></div>"><div></div></a></td>
<td .. ><a href="a.com/"A&B"">"A&B"</a></td>
<td .. >NA</td>
...
在‘latex’模式下使用带有escape
的formatter
。
>>> df = pd.DataFrame([["123"], ["~ ^"], ["$%#"]])
>>> df.style.format("\\textbf{{{}}}", escape="latex").to_latex()
...
\begin{tabular}{ll}
& 0 \\
0 & \textbf{123} \\
1 & \textbf{\textasciitilde \space \textasciicircum } \\
2 & \textbf{\$\%\#} \\
\end{tabular}
在‘latex-math’模式下应用escape
。在下面的示例中,我们使用字符$
进入数学模式。
>>> df = pd.DataFrame([[r"$\sum_{i=1}^{10} a_i$ a~b $\alpha \
... = \frac{\beta}{\zeta²}$"], ["%#^ $ \$x² $"]])
>>> df.style.format(escape="latex-math").to_latex()
...
\begin{tabular}{ll}
& 0 \\
0 & $\sum_{i=1}^{10} a_i$ a\textasciitilde b $\alpha = \frac{\beta}{\zeta²}$ \\
1 & \%\#\textasciicircum \space $ \$x² $ \\
\end{tabular}
我们可以使用字符\(
进入数学模式,使用字符\)
关闭数学模式。
>>> df = pd.DataFrame([[r"\(\sum_{i=1}^{10} a_i\) a~b \(\alpha \
... = \frac{\beta}{\zeta²}\)"], ["%#^ \( \$x² \)"]])
>>> df.style.format(escape="latex-math").to_latex()
...
\begin{tabular}{ll}
& 0 \\
0 & \(\sum_{i=1}^{10} a_i\) a\textasciitilde b \(\alpha
= \frac{\beta}{\zeta²}\) \\
1 & \%\#\textasciicircum \space \( \$x² \) \\
\end{tabular}
如果在一个 DataFrame 单元格中同时使用数学公式的简写形式,将应用带有符号$
的简写形式。
>>> df = pd.DataFrame([[r"\( x² \) $x²$"], \
... [r"$\frac{\beta}{\zeta}$ \(\frac{\beta}{\zeta}\)"]])
>>> df.style.format(escape="latex-math").to_latex()
...
\begin{tabular}{ll}
& 0 \\
0 & \textbackslash ( x\textasciicircum 2 \textbackslash ) $x²$ \\
1 & $\frac{\beta}{\zeta}$ \textbackslash (\textbackslash
frac\{\textbackslash beta\}\{\textbackslash zeta\}\textbackslash ) \\
\end{tabular}
Pandas 定义了一个数字格式伪 CSS 属性,而不是.format
方法来创建to_excel
允许的格式。请注意,分号是 CSS 受保护字符,但在 Excel 的格式字符串中用作分隔符。在定义格式时,请将分号替换为分节分隔符字符(ASCII-245)。
>>> df = pd.DataFrame({"A": [1, 0, -1]})
>>> pseudo_css = "number-format: 0§Red§-§@;"
>>> filename = "formatted_file.xlsx"
>>> df.style.map(lambda v: pseudo_css).to_excel(filename)
pandas.io.formats.style.Styler.format_index
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.format_index.html
Styler.format_index(formatter=None, axis=0, level=None, na_rep=None, precision=None, decimal='.', thousands=None, escape=None, hyperlinks=None)
格式化索引标签或列标题的文本显示值。
1.4.0 版中的新功能。
参数:
formatterstr, callable, dict or None
定义值如何显示的对象。请参见注意事项。
axis
是否将格式化器应用于索引或列标题。
levelint, str, list
应用通用格式化器的级别。
na_repstr, optional
用于表示缺失值的表示。如果na_rep
为 None,则不应用特殊格式。
precisionint, optional
用于显示目的的浮点精度,如果不是由指定的formatter
确定。
decimalstr, default “.”
用作浮点数、复数和整数的小数分隔符的字符。
thousandsstr, optional, default None
用作浮点数、复数和整数的千位分隔符的字符。
escapestr, optional
使用‘html’将单元格显示字符串中的字符&
、<
、>
、'
和"
替换为 HTML 安全序列。使用‘latex’将单元格显示字符串中的字符&
、%
、$
、#
、_
、{
、}
、~
、^
和\
替换为 LaTeX 安全序列。转义在formatter
之前完成。
hyperlinks, optional
将包含https://、http://、ftp://或 www.的字符串模式转换为 HTML 标签,作为可点击的 URL 超链接(如果是“html”),或者转换为 LaTeX href 命令(如果是“latex”)。
返回:
Styler
另请参见
格式化数据单元格的文本显示值。
注意
此方法为 DataFrame 的索引或列标题中的每个级别标签分配一个格式化函数formatter
。如果formatter
为None
,则使用默认格式化器。如果是可调用的,则该函数应以标签值作为输入并返回可显示的表示,例如字符串。如果formatter
给出为字符串,则假定为有效的 Python 格式规范,并将其包装为可调用的string.format(x)
。如果给出一个dict
,键应对应于 MultiIndex 级别编号或名称,值应为字符串或可调用对象,如上所述。
默认格式化器当前使用 pandas 显示精度来表示浮点数和复数,除非在此处使用precision
参数。默认格式化器不会调整缺失值的表示,除非使用na_rep
参数。
level
参数定义了要应用该方法的 MultiIndex 的哪些级别。如果 formatter
参数以字典形式给出,但不包括 level 参数中的所有级别,则这些未指定的级别将应用默认的格式化程序。在 formatter 字典中明确排除在 level 参数中的任何级别将被忽略。
当使用 formatter
字符串时,dtype 必须兼容,否则会引发 ValueError。
警告
当使用输出格式 Styler.to_excel 时,Styler.format_index 将被忽略,因为 Excel 和 Python 有不同的格式化结构。但是,可以使用数字格式伪 CSS 属性来强制 Excel 允许的格式化。请参阅 Styler.format 的文档。
示例
使用 na_rep
和 precision
与默认的 formatter
>>> df = pd.DataFrame([[1, 2, 3]], columns=[2.0, np.nan, 4.0])
>>> df.style.format_index(axis=1, na_rep='MISS', precision=3)
2.000 MISS 4.000
0 1 2 3
在级别中使用 formatter
规范一致的 dtype
>>> df.style.format_index('{:.2f}', axis=1, na_rep='MISS')
2.00 MISS 4.00
0 1 2 3
对未指定级别使用默认的 formatter
>>> df = pd.DataFrame([[1, 2, 3]],
... columns=pd.MultiIndex.from_arrays([["a", "a", "b"],[2, np.nan, 4]]))
>>> df.style.format_index({0: lambda v: v.upper()}, axis=1, precision=1)
...
A B
2.0 nan 4.0
0 1 2 3
使用可调用的 formatter
函数。
>>> func = lambda s: 'STRING' if isinstance(s, str) else 'FLOAT'
>>> df.style.format_index(func, axis=1, na_rep='MISS')
...
STRING STRING
FLOAT MISS FLOAT
0 1 2 3
使用带有 HTML escape
和 na_rep
的 formatter
。
>>> df = pd.DataFrame([[1, 2, 3]], columns=['"A"', 'A&B', None])
>>> s = df.style.format_index('$ {0}', axis=1, escape="html", na_rep="NA")
...
<th .. >$ "A"</th>
<th .. >$ A&B</th>
<th .. >NA</td>
...
使用带有 LaTeX escape
的 formatter
。
>>> df = pd.DataFrame([[1, 2, 3]], columns=["123", "~", "$%#"])
>>> df.style.format_index("\\textbf{{{}}}", escape="latex", axis=1).to_latex()
...
\begin{tabular}{lrrr}
{} & {\textbf{123}} & {\textbf{\textasciitilde }} & {\textbf{\$\%\#}} \\
0 & 1 & 2 & 3 \\
\end{tabular}
pandas.io.formats.style.Styler.relabel_index
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.relabel_index.html
Styler.relabel_index(labels, axis=0, level=None)
重新标记索引或列标题键,以显示一组指定的值。
从版本 1.5.0 开始。
参数:
labelslist-like or Index
要显示的新标签。必须与未隐藏的基础值具有相同的长度。
axis
应用于索引或列。
levelint, str, list, optional
要应用新标签的级别。如果为 None,则将应用于未隐藏的索引或 MultiIndex 的所有级别。
返回:
Styler
另请参见
Styler.format_index
格式化索引或列标题的文本显示值。
Styler.hide
隐藏索引、列标题或指定数据以便显示。
注意
作为 Styler 的一部分,此方法允许完全用户指定索引的显示,而不影响底层 DataFrame 数据、索引或列标题。这意味着保持了索引的灵活性,同时最终显示是可定制的。
由于 Styler 被设计为逐步构建的方法链,因此此方法被调整以响应当前指定的隐藏元素。这很有用,因为这意味着如果大部分索引或列标题已被隐藏,则不必指定所有新标签。以下产生等效的显示(请注意每种情况下labels
的长度)。
# relabel first, then hide
df = pd.DataFrame({"col": ["a", "b", "c"]})
df.style.relabel_index(["A", "B", "C"]).hide([0,1])
# hide first, then relabel
df = pd.DataFrame({"col": ["a", "b", "c"]})
df.style.hide([0,1]).relabel_index(["C"])
在以下情况之一中应使用此方法,而不是Styler.format_index()
(请参见示例):
- 需要一组指定的标签,这些标签不是基础索引键的函数。
- 底层索引键的功能需要一个计数变量,例如枚举时可用的变量。
示例
基本用法
>>> df = pd.DataFrame({"col": ["a", "b", "c"]})
>>> df.style.relabel_index(["A", "B", "C"])
col
A a
B b
C c
与预隐藏元素链接
>>> df.style.hide([0,1]).relabel_index(["C"])
col
C c
使用 MultiIndex
>>> midx = pd.MultiIndex.from_product([[0, 1], [0, 1], [0, 1]])
>>> df = pd.DataFrame({"col": list(range(8))}, index=midx)
>>> styler = df.style
col
0 0 0 0
1 1
1 0 2
1 3
1 0 0 4
1 5
1 0 6
1 7
>>> styler.hide((midx.get_level_values(0)==0)|(midx.get_level_values(1)==0))
...
>>> styler.hide(level=[0,1])
>>> styler.relabel_index(["binary6", "binary7"])
col
binary6 6
binary7 7
我们也可以通过首先进行索引然后重新标记来实现上述功能。
>>> styler = df.loc[[(1,1,0), (1,1,1)]].style
>>> styler.hide(level=[0,1]).relabel_index(["binary6", "binary7"])
...
col
binary6 6
binary7 7
定义一个使用枚举计数器的格式化函数。还要注意,对于字符串标签,索引键的值会传递,因此它也可以插入到标签中,使用花括号(如果字符串已经格式化,则使用双花括号),
>>> df = pd.DataFrame({"samples": np.random.rand(10)})
>>> styler = df.loc[np.random.randint(0,10,3)].style
>>> styler.relabel_index([f"sample{i+1} ({{}})" for i in range(3)])
...
samples
sample1 (5) 0.315811
sample2 (0) 0.495941
sample3 (2) 0.067946
pandas.io.formats.style.Styler.hide
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.hide.html
Styler.hide(subset=None, axis=0, level=None, names=False)
隐藏整个索引/列标题,或从显示中隐藏特定行/列。
1.4.0 版本中新增。
参数:
subsetlabel, array-like, IndexSlice, optional
在 DataFrame.loc[data
选择隐藏的行/列。
axis
应用于索引或列。
levelint, str, list
在隐藏整个索引/列标题时要隐藏的多级索引中的级别。不能与subset
同时使用。
namesbool
是否隐藏索引/列标题中级别名称(如果至少有一个级别保持可见)。
返回:
Styler
注意
警告
此方法仅适用于输出方法to_html
、to_string
和to_latex
。
其他输出方法,包括to_excel
,会忽略此隐藏方法并显示所有数据。
此方法具有多种功能,取决于subset
、level
和names
参数的组合(请参见示例)。axis
参数仅用于控制方法是应用于行标题还是列标题:
参数组合
subset |
level |
names |
效果 |
---|---|---|---|
None | None | False | 轴-索引完全隐藏。 |
None | None | True | 仅隐藏轴-索引名称。 |
None | Int, Str, List | False | 指定的轴-多级索引级别完全隐藏。 |
None | Int, Str, List | True | 指定的轴-多级索引级别完全隐藏,剩余轴-多级索引级别的名称。 |
Subset | None | False | 指定的数据行/列被隐藏,但轴-索引本身和名称保持不变。 |
Subset | None | True | 指定的数据行/列和轴-索引名称被隐藏,但轴-索引本身保持不变。 |
Subset | Int, Str, List | Boolean | ValueError: 不能同时提供subset 和level 。 |
请注意,此方法仅隐藏已识别的元素,因此可以链接以依次隐藏多个元素。
示例
简单应用隐藏特定行:
>>> df = pd.DataFrame([[1,2], [3,4], [5,6]], index=["a", "b", "c"])
>>> df.style.hide(["a", "b"])
0 1
c 5 6
隐藏索引并保留数据值:
>>> midx = pd.MultiIndex.from_product([["x", "y"], ["a", "b", "c"]])
>>> df = pd.DataFrame(np.random.randn(6,6), index=midx, columns=midx)
>>> df.style.format("{:.1f}").hide()
x y
a b c a b c
0.1 0.0 0.4 1.3 0.6 -1.4
0.7 1.0 1.3 1.5 -0.0 -0.2
1.4 -0.8 1.6 -0.2 -0.4 -0.3
0.4 1.0 -0.2 -0.8 -1.2 1.1
-0.6 1.2 1.8 1.9 0.3 0.3
0.8 0.5 -0.3 1.2 2.2 -0.8
在多级索引中隐藏特定行,但保留索引:
>>> df.style.format("{:.1f}").hide(subset=(slice(None), ["a", "c"]))
...
x y
a b c a b c
x b 0.7 1.0 1.3 1.5 -0.0 -0.2
y b -0.6 1.2 1.8 1.9 0.3 0.3
通过链接隐藏特定行和索引:
>>> df.style.format("{:.1f}").hide(subset=(slice(None), ["a", "c"])).hide()
...
x y
a b c a b c
0.7 1.0 1.3 1.5 -0.0 -0.2
-0.6 1.2 1.8 1.9 0.3 0.3
隐藏特定级别:
>>> df.style.format("{:,.1f}").hide(level=1)
x y
a b c a b c
x 0.1 0.0 0.4 1.3 0.6 -1.4
0.7 1.0 1.3 1.5 -0.0 -0.2
1.4 -0.8 1.6 -0.2 -0.4 -0.3
y 0.4 1.0 -0.2 -0.8 -1.2 1.1
-0.6 1.2 1.8 1.9 0.3 0.3
0.8 0.5 -0.3 1.2 2.2 -0.8
仅隐藏索引级别名称:
>>> df.index.names = ["lev0", "lev1"]
>>> df.style.format("{:,.1f}").hide(names=True)
x y
a b c a b c
x a 0.1 0.0 0.4 1.3 0.6 -1.4
b 0.7 1.0 1.3 1.5 -0.0 -0.2
c 1.4 -0.8 1.6 -0.2 -0.4 -0.3
y a 0.4 1.0 -0.2 -0.8 -1.2 1.1
b -0.6 1.2 1.8 1.9 0.3 0.3
c 0.8 0.5 -0.3 1.2 2.2 -0.8
示例都会产生与axis="columns"
等效的转置效果。
pandas.io.formats.style.Styler.concat
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.concat.html
Styler.concat(other)
添加另一个样式器以将输出组合成单个表格。
自 1.5.0 版本新增。
参数:
其他样式器
其他样式器对象已经被样式化和格式化。此样式器的数据必须与原始数据的列相同,并且索引级别的数量也必须相同才能正确呈现。
返回:
样式器
注意事项
此方法的目的是通过其他可能有用但不符合原始结构的指标来扩展现有的样式化数据框。例如,添加小计行,或显示诸如均值、方差或计数之类的指标。
使用 apply
、map
、apply_index
和 map_index
应用的样式以及使用 format
和 format_index
应用的格式将被保留。
警告
只有 to_html
、to_string
和 to_latex
输出方法当前与拼接的样式器一起使用。
其他输出方法,包括 to_excel
,不适用于 拼接的样式器。
应注意以下内容:
table_styles
、table_attributes
、caption
和uuid
都从原始样式器继承,而不是从other
继承。- 隐藏的列和隐藏的索引级别将从原始样式器继承
css
将从原始样式器继承,并且键data
、row_heading
和row
的值将以foot0_
开头。如果链接更多的拼接,它们的样式将以foot1_
、foot2_
等开头,如果一个拼接的样式有另一个拼接的样式,第二个样式将以foot{parent}_foot{child}_
开头。
一个常见的用例是使用 DataFrame.agg
或者通过 DataFrame.describe
描述的统计信息来连接用户定义的函数。见示例。
示例
一个常见的用例是通过 DataFrame.agg
中计算的方法添加总行或其他内容。
>>> df = pd.DataFrame([[4, 6], [1, 9], [3, 4], [5, 5], [9, 6]],
... columns=["Mike", "Jim"],
... index=["Mon", "Tue", "Wed", "Thurs", "Fri"])
>>> styler = df.style.concat(df.agg(["sum"]).style)
由于拼接的对象是样式器,因此可以使用现有功能对其进行条件格式化以及对原始数据进行格式化。
>>> descriptors = df.agg(["sum", "mean", lambda s: s.dtype])
>>> descriptors.index = ["Total", "Average", "dtype"]
>>> other = (descriptors.style
... .highlight_max(axis=1, subset=(["Total", "Average"], slice(None)))
... .format(subset=("Average", slice(None)), precision=2, decimal=",")
... .map(lambda v: "font-weight: bold;"))
>>> styler = (df.style
... .highlight_max(color="salmon")
... .set_table_styles([{"selector": ".foot_row0",
... "props": "border-top: 1px solid black;"}]))
>>> styler.concat(other)
当 other
的索引级别少于原始样式器时,可以扩展 other
中的索引,并使用占位符级别。
>>> df = pd.DataFrame([[1], [2]],
... index=pd.MultiIndex.from_product([[0], [1, 2]]))
>>> descriptors = df.agg(["sum"])
>>> descriptors.index = pd.MultiIndex.from_product([[""], descriptors.index])
>>> df.style.concat(descriptors.style)
pandas.io.formats.style.Styler.set_td_classes
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.set_td_classes.html
Styler.set_td_classes(classes)
设置 <td>
HTML 元素的 class
属性。
参数:
classesDataFrame
包含将被翻译为 CSS 类的字符串的 DataFrame,由相同的列和索引键值映射,这些键值必须存在于底层的 Styler 数据上。None
、NaN
值和空字符串将被忽略,不会影响呈现的 HTML。
返回:
Styler
另请参阅
Styler.set_table_styles
设置包含在 <style>
HTML 元素中的表样式。
Styler.set_table_attributes
设置添加到 <table>
HTML 元素中的表属性。
注意
可与 Styler.set_table_styles
结合使用,以定义不引用外部 CSS 文件的内部 CSS 解决方案。
示例
>>> df = pd.DataFrame(data=[[1, 2, 3], [4, 5, 6]], columns=["A", "B", "C"])
>>> classes = pd.DataFrame([
... ["min-val red", "", "blue"],
... ["red", None, "blue max-val"]
... ], index=df.index, columns=df.columns)
>>> df.style.set_td_classes(classes)
使用 MultiIndex 列和作为底层 Styler 子集的类 DataFrame,
>>> df = pd.DataFrame([[1,2],[3,4]], index=["a", "b"],
... columns=[["level0", "level0"], ["level1a", "level1b"]])
>>> classes = pd.DataFrame(["min-val"], index=["a"],
... columns=[["level0"],["level1a"]])
>>> df.style.set_td_classes(classes)
具有新附加的 CSS 类的输出形式,
>>> from pandas.io.formats.style import Styler
>>> df = pd.DataFrame([[1]])
>>> css = pd.DataFrame([["other-class"]])
>>> s = Styler(df, uuid="_", cell_ids=False).set_td_classes(css)
>>> s.hide(axis=0).to_html()
'<style type="text/css"></style>'
'<table id="T__">'
' <thead>'
' <tr><th class="col_heading level0 col0" >0</th></tr>'
' </thead>'
' <tbody>'
' <tr><td class="data row0 col0 other-class" >1</td></tr>'
' </tbody>'
'</table>'
pandas.io.formats.style.Styler.set_table_styles
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.set_table_styles.html
Styler.set_table_styles(table_styles=None, axis=0, overwrite=True, css_class_names=None)
设置包含在<style>
HTML 元素中的表样式。
此函数可用于为整个表、列、行或特定的 HTML 选择器设置样式。
参数:
table_styles列表或字典
如果提供的是一个列表,则每个单独的table_style
应该是一个带有selector
和props
键的字典。selector
应该是将应用样式的 CSS 选择器(自动由表的 UUID 前缀)并且props
应该是一个包含(attribute, value)
的元组列表。如果提供的是一个字典,则字典键应该对应于列名或索引值,具体取决于指定的轴参数。这些将被映射到行或列 CSS 选择器。作为字典键的 MultiIndex 值应该以它们各自的元组形式给出。字典值应该是一个列表,其形式如上所述,其中包含将应用于指定行或列的 CSS 选择器和 props。
axis,默认 0
应用于每列(axis=0
或'index'
)或每行(axis=1
或'columns'
)。仅当table_styles
为字典时使用。
overwrite布尔值,默认 True
如果选择器相交,则样式将被替换为 True,否则将被扩展为 False。 CSS 规则将被保留,因此如果选择器相交,最近设置的样式将占主导地位。
css_class_names字典,可选
用于替换下述默认 CSS 类的字符串字典。
版本 1.4.0 中的新功能。
返回:
Styler
另请参阅
Styler.set_td_classes
设置添加到<td>
HTML 元素的class
属性的字符串的 DataFrame。
Styler.set_table_attributes
设置添加到<table>
HTML 元素的表属性。
注意
默认的 CSS 类字典,其值可以被替换如下:
css_class_names = {"row_heading": "row_heading",
"col_heading": "col_heading",
"index_name": "index_name",
"col": "col",
"row": "row",
"col_trim": "col_trim",
"row_trim": "row_trim",
"level": "level",
"data": "data",
"blank": "blank",
"foot": "foot"}
示例
>>> df = pd.DataFrame(np.random.randn(10, 4),
... columns=['A', 'B', 'C', 'D'])
>>> df.style.set_table_styles(
... [{'selector': 'tr:hover',
... 'props': [('background-color', 'yellow')]}]
... )
或使用 CSS 字符串
>>> df.style.set_table_styles(
... [{'selector': 'tr:hover',
... 'props': 'background-color: yellow; font-size: 1em;'}]
... )
按名称添加列样式
>>> df.style.set_table_styles({
... 'A': [{'selector': '',
... 'props': [('color', 'red')]}],
... 'B': [{'selector': 'td',
... 'props': 'color: blue;'}]
... }, overwrite=False)
添加行样式
>>> df.style.set_table_styles({
... 0: [{'selector': 'td:hover',
... 'props': [('font-size', '25px')]}]
... }, axis=1, overwrite=False)
查看 Table Visualization 用户指南以获取更多详细信息。
pandas.io.formats.style.Styler.set_table_attributes
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.set_table_attributes.html
Styler.set_table_attributes(attributes)
设置添加到<table>
HTML 元素的表属性。
这些是除了默认的id
属性之外的项目。
参数:
属性str
返回:
Styler
另请参阅
Styler.set_table_styles
设置包含在<style>
HTML 元素中的表样式。
Styler.set_td_classes
设置添加到<td>
HTML 元素的class
属性的字符串 DataFrame。
示例
>>> df = pd.DataFrame(np.random.randn(10, 4))
>>> df.style.set_table_attributes('class="pure-table"')
# ... <table class="pure-table"> ...
pandas.io.formats.style.Styler.set_tooltips
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.set_tooltips.html
Styler.set_tooltips(ttips, props=None, css_class=None)
在生成:hover
工具提示的Styler
上设置字符串的 DataFrame。
这些基于字符串的工具提示仅适用于<td>
HTML 元素,不能用于列或索引标题。
自 1.3.0 版本开始。
参数:
ttipsDataFrame
包含将被转换为工具提示的字符串的 DataFrame,由相同列和索引值映射,这些值必须存在于底层 Styler 数据中。None
、NaN 值和空字符串将被忽略,不会影响呈现的 HTML。
props类似列表或字符串,可选
(attr, value)元组列表或有效的 CSS 字符串。如果为None
,则采用注释中描述的内部默认值。
css_classstr,可选
CSS 中使用的工具提示类的名称,应符合 HTML 标准。仅在将工具提示与外部 CSS 集成时有用。如果为None
,则使用内部默认值‘pd-t’。
返回:
Styler
注释
通过向每个数据单元格添加,然后操纵表级 CSS 以附加伪悬停和伪后选择器来生成所需的结果来创建工具提示。
工具提示 CSS 类的默认属性为:
-
visibility: hidden
-
位置:绝对
-
z-index:1
-
背景颜色:黑色
-
颜色:白色
-
transform:translate(-20px, -20px)
属性‘visibility: hidden;’是悬停功能的关键先决条件,应始终包含在任何手动属性规范中,使用props
参数。
工具提示并非旨在高效,对于较大的表格,可能会添加大量额外的 HTML,因为它们还要求cell_ids
强制为 True。
示例
基本应用
>>> df = pd.DataFrame(data=[[0, 1], [2, 3]])
>>> ttips = pd.DataFrame(
... data=[["Min", ""], [np.nan, "Max"]], columns=df.columns, index=df.index
... )
>>> s = df.style.set_tooltips(ttips).to_html()
可选控制工具提示的视觉显示
>>> df.style.set_tooltips(ttips, css_class='tt-add', props=[
... ('visibility', 'hidden'),
... ('position', 'absolute'),
... ('z-index', 1)])
>>> df.style.set_tooltips(ttips, css_class='tt-add',
... props='visibility:hidden; position:absolute; z-index:1;')
...
pandas.io.formats.style.Styler.set_caption
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.set_caption.html
Styler.set_caption(caption)
设置添加到<caption>
HTML 元素的文本。
参数:
captionstr,元组,列表
对于 HTML 输出,要么使用字符串输入,要么使用元组的第一个元素。对于 LaTeX,字符串输入提供标题,而附加的元组输入允许按顺序提供完整标题和简短标题。
返回:
样式器
示例
>>> df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
>>> df.style.set_caption("test")
请参阅:表格可视化以获取更多示例。
pandas.io.formats.style.Styler.set_sticky
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.set_sticky.html
Styler.set_sticky(axis=0, pixel_size=None, levels=None)
添加 CSS 以永久显示索引或列标题在滚动框架中。
参数:
axis,默认为 0
是否使索引或列标题粘性。
pixel_size整型,可选
在粘住 MultiIndex(或具有命名索引)时,需要配置索引单元格的宽度或列标题单元格的高度。分别默认为 75 和 25。
levels整型,字符串,列表,可选
如果 axis
是多级索引,则特定级别将粘住。如果为 None
,将粘住所有级别。
返回值:
样式化器
注意
此方法使用 CSS 的 'position: sticky;' 属性进行显示。它设计用于与可见轴一起工作,因此两者都:
- styler.set_sticky(axis=”index”).hide(axis=”index”)
- styler.set_sticky(axis=”columns”).hide(axis=”columns”)
由于缺少元素的 CSS 控制可能导致奇怪的行为。
示例
>>> df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
>>> df.style.set_sticky(axis="index")
请参见:表格可视化 以获取更多示例。
pandas.io.formats.style.Styler.set_properties
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.set_properties.html
Styler.set_properties(subset=None, **kwargs)
为给定的子集的每个<td>
HTML 元素设置定义的 CSS 属性。
参数:
subset标签,类似数组,IndexSlice,可选
一个有效的 2D 输入到 DataFrame.loc[data
在应用函数之前。
****kwargs**dict
一个属性,值对的字典,用于设置每个单元格。
返回:
Styler
注意
这是一个方便的方法,它包装了Styler.map()
调用一个独立于数据的返回 CSS 属性的函数。
示例
>>> df = pd.DataFrame(np.random.randn(10, 4))
>>> df.style.set_properties(color="white", align="right")
>>> df.style.set_properties(**{'background-color': 'yellow'})
查看表可视化用户指南以获取更多详细信息。
pandas.io.formats.style.Styler.set_uuid
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.set_uuid.html
Styler.set_uuid(uuid)
设置应用于 HTML 元素的 id
属性的 uuid。
参数:
uuidstr
返回:
Styler
注意
几乎所有表格内的 HTML 元素,包括 <table>
元素在内,都被分配了 id
属性。其格式为 T_uuid_<extra>
,其中 <extra>
通常是一个更具体的标识符,例如 row1_col2
。
示例
>>> df = pd.DataFrame([[1, 2], [3, 4]], index=['A', 'B'], columns=['c1', 'c2'])
您可以通过以下方式获取 id 属性:
>>> print((df).style.to_html())
要为列 c1 添加标题,其 id 为 T_20a7d_level0_col0:
>>> df.style.set_uuid("T_20a7d_level0_col0")
... .set_caption("Test")
请参见:表格可视化 以获取更多示例。
pandas.io.formats.style.Styler.clear
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.clear.html
Styler.clear()
重置 Styler
,移除任何先前应用的样式。
返回 None。
示例
>>> df = pd.DataFrame({'A': [1, 2], 'B': [3, np.nan]})
在添加任何样式之后:
>>> df.style.highlight_null(color='yellow')
使用以下方法将其移除:
>>> df.style.clear()
请参阅:表格可视化 以获取更多示例。
pandas.io.formats.style.Styler.pipe
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.pipe.html
Styler.pipe(func, *args, **kwargs)
应用 func(self, *args, **kwargs)
,并返回结果。
参数:
func函数
函数应用到 Styler 上。或者,一个(callable, keyword)
元组,其中 keyword
是一个字符串,表示 callable
期望的 Styler 的关键字。
*args可选
传递给 func 的参数。
****kwargs**可选
传递给 func
的关键字参数的字典。
返回值:
对象
func
的返回值。
另请参阅
DataFrame.pipe
DataFrame 的类似方法。
Styler.apply
对列、行或表进行 CSS 样式化函数的应用。
注释
与 DataFrame.pipe()
类似,此方法可以简化对 styler 应用多个用户定义函数的操作。而不是编写:
f(g(df.style.format(precision=3), arg1=a), arg2=b, arg3=c)
用户可以编写:
(df.style.format(precision=3)
.pipe(g, arg1=a)
.pipe(f, arg2=b, arg3=c))
特别是,这允许用户定义接受 styler 对象以及其他参数的函数,并在进行样式更改后返回 styler(例如调用 Styler.apply()
或 Styler.set_properties()
)。
示例
常见用法
一个常见的用法模式是预先定义样式化操作,这些操作可以轻松应用于单个 pipe
调用中的通用 styler。
>>> def some_highlights(styler, min_color="red", max_color="blue"):
... styler.highlight_min(color=min_color, axis=None)
... styler.highlight_max(color=max_color, axis=None)
... styler.highlight_null()
... return styler
>>> df = pd.DataFrame([[1, 2, 3, pd.NA], [pd.NA, 4, 5, 6]], dtype="Int64")
>>> df.style.pipe(some_highlights, min_color="green")
由于该方法返回一个 Styler
对象,因此可以像直接应用底层高亮器一样,将其与其他方法链接起来。
>>> (df.style.format("{:.1f}")
... .pipe(some_highlights, min_color="green")
... .highlight_between(left=2, right=5))
高级用法
有时可能需要预先定义样式化函数,但在这些函数依赖于 styler、数据或上下文的情况下。由于 Styler.use
和 Styler.export
设计为非数据相关,因此不能用于此目的。此外,Styler.apply
和 Styler.format
类型方法不具有上下文感知能力,因此解决方案是使用 pipe
动态包装此功能。
假设我们想编写一个通用样式化函数,用于高亮显示多索引的最终级别。索引中级别的数量是动态的,因此我们需要 Styler
上下文来定义级别。
>>> def highlight_last_level(styler):
... return styler.apply_index(
... lambda v: "background-color: pink; color: yellow", axis="columns",
... level=styler.columns.nlevels-1
... )
>>> df.columns = pd.MultiIndex.from_product([["A", "B"], ["X", "Y"]])
>>> df.style.pipe(highlight_last_level)
此外,假设我们希望在列头中高亮显示任何列中存在缺失数据的列。在这种情况下,我们需要数据对象本身来确定对列标题的影响。
>>> def highlight_header_missing(styler, level):
... def dynamic_highlight(s):
... return np.where(
... styler.data.isna().any(), "background-color: red;", ""
... )
... return styler.apply_index(dynamic_highlight, axis=1, level=level)
>>> df.style.pipe(highlight_header_missing, level=1)
pandas.io.formats.style.Styler.highlight_null
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.highlight_null.html
Styler.highlight_null(color='red', subset=None, props=None)
用样式突出缺失值。
参数:
colorstr,默认为 'red'
用于突出显示的背景颜色。
在版本 1.5.0 中新增。
subset标签,数组样式,IndexSlice,可选
一个有效的 DataFrame.loc[data
。
propsstr,默认为 None
用于突出显示的 CSS 属性。如果给定了 props
,则不使用 color
。
在版本 1.3.0 中新增。
返回:
Styler
另请参阅
Styler.highlight_max
用样式突出最大值。
Styler.highlight_min
用样式突出最小值。
Styler.highlight_between
用样式突出定义的范围。
Styler.highlight_quantile
用样式突出定义的分位数值。
示例
>>> df = pd.DataFrame({'A': [1, 2], 'B': [3, np.nan]})
>>> df.style.highlight_null(color='yellow')
请参见:表可视化 以获取更多示例。
pandas.io.formats.style.Styler.highlight_max
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.highlight_max.html
Styler.highlight_max(subset=None, color='yellow', axis=0, props=None)
用一种风格突出显示最大值。
参数:
subset 标签,类数组,IndexSlice,可选
有效的二维输入到 DataFrame.loc[data
。
color 字符串,默认为 ‘yellow’
用于突出显示的背景颜色。
axis,默认为 0
使用 axis=0
或 'index'
对每一列应用,使用 axis=1
或 'columns'
对每一行应用,或者一次性对整个 DataFrame 应用 axis=None
。
props 字符串,默认为 None
用于突出显示的 CSS 属性。如果给出了 props
,则不使用 color
。
自版本 1.3.0 新增。
返回:
Styler
请参阅
Styler.highlight_null
用一种风格突出显示缺失值。
Styler.highlight_min
用一种风格突出显示最小值。
Styler.highlight_between
用一种风格突出显示定义范围。
Styler.highlight_quantile
用一种风格突出显示由分位数定义的值。
示例
>>> df = pd.DataFrame({'A': [2, 1], 'B': [3, 4]})
>>> df.style.highlight_max(color='yellow')
请参阅:表格可视化 以获取更多示例。
pandas.io.formats.style.Styler.highlight_min
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.highlight_min.html
Styler.highlight_min(subset=None, color='yellow', axis=0, props=None)
使用样式突出显示最小值。
参数:
subsetlabel,array-like,IndexSlice,可选
一个有效的 2d 输入到 DataFrame.loc[data
。
colorstr,默认为 'yellow'
用于突出显示的背景颜色。
axis,默认为 0
可应用于每列(axis=0
或 'index'
)、每行(axis=1
或 'columns'
)或一次应用于整个 DataFrame(axis=None
)。
propsstr,默认为 None
用于突出显示的 CSS 属性。如果给定了 props
,则不使用 color
。
自 1.3.0 版本新增。
返回:
Styler
另请参阅
使用样式突出显示缺失值。
使用样式突出显示最大值。
使用样式突出显示定义的范围。
使用样式突出显示由分位数定义的值。
示例
>>> df = pd.DataFrame({'A': [2, 1], 'B': [3, 4]})
>>> df.style.highlight_min(color='yellow')
请参阅:表可视化 获取更多示例。
pandas.io.formats.style.Styler.highlight_between
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.highlight_between.html
Styler.highlight_between(subset=None, color='yellow', axis=0, left=None, right=None, inclusive='both', props=None)
用样式突出显示定义范围。
新版本 1.3.0 中新增。
参数:
subset标签,类数组,IndexSlice,可选
有效的 2d 输入为 DataFrame.loc[data
。
colorstr,默认为 ‘yellow’
用于突出显示的背景颜色。
axis,默认为 0
如果 left
或 right
作为序列给出,则沿着应用这些边界的轴。请参阅示例。
left标量或类似日期时间,或序列或类数组,默认为 None
定义范围的左边界。
right标量或类似日期时间,或序列或类数组,默认为 None
定义范围的右边界。
inclusive
识别边界是封闭还是开放的。
propsstr,默认为 None
用于突出显示的 CSS 属性。如果给定了 props
,则不使用 color
。
返回:
Styler
另请参阅
Styler.highlight_null
用样式突出显示缺失值。
Styler.highlight_max
用样式突出显示最大值。
Styler.highlight_min
用样式突出显示最小值。
Styler.highlight_quantile
用样式突出显示由分位数定义的值。
注意
如果 left
为 None
,则仅应用右边界。如果 right
为 None
,则仅应用左边界。如果两者都为 None
,则突出显示所有值。
如果 left
或 right
作为序列或类数组对象提供,则只需要 axis
来对齐形状。如果 left
和 right
都是标量,则所有 axis
输入将给出相同结果。
此函数仅适用于兼容的 dtypes
。例如,类似日期时间的区域只能使用等效的类似日期时间的 left
和 right
参数。使用 subset
来控制具有多个 dtypes
的区域。
示例
基本用法
>>> df = pd.DataFrame({
... 'One': [1.2, 1.6, 1.5],
... 'Two': [2.9, 2.1, 2.5],
... 'Three': [3.1, 3.2, 3.8],
... })
>>> df.style.highlight_between(left=2.1, right=2.9)
使用沿着 axis
的范围输入序列,在这种情况下为每列单独设置 left
和 right
>>> df.style.highlight_between(left=[1.4, 2.4, 3.4], right=[1.6, 2.6, 3.6],
... axis=1, color="#fffd75")
使用 axis=None
并提供 left
参数作为与输入 DataFrame 匹配的数组,同时使用常量 right
>>> df.style.highlight_between(left=[[2,2,3],[2,2,3],[3,3,3]], right=3.5,
... axis=None, color="#fffd75")
使用 props
替代默认的背景颜色
>>> df.style.highlight_between(left=1.5, right=3.5,
... props='font-weight:bold;color:#e83e8c')
pandas.io.formats.style.Styler.highlight_quantile
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.highlight_quantile.html
Styler.highlight_quantile(subset=None, color='yellow', axis=0, q_left=0.0, q_right=1.0, interpolation='linear', inclusive='both', props=None)
用样式突出显示由分位数定义的值。
新版本 1.3.0 中新增。
参数:
subset标签,类似数组,IndexSlice,可选
一个有效的 DataFrame.loc[
colorstr,默认值 ‘yellow’
用于突出显示的背景颜色。
axis,默认值 0
用于确定并突出显示分位数的轴。如果 None
,则分位数是在整个 DataFrame 上测量的。参见示例。
q_leftfloat,默认值 0
目标分位数范围的左边界,位于 [0, q_right)。
q_rightfloat,默认值 1
目标分位数范围的右边界,位于 (q_left, 1]。
interpolation
传递给 Series.quantile
或 DataFrame.quantile
以进行分位数估计的参数。
inclusive
确定分位数边界是封闭还是开放。
propsstr,默认值 None
用于突出显示的 CSS 属性。如果给定了 props
,则不使用 color
。
返回:
Styler
另请参见
Styler.highlight_null
用样式突出显示缺失值。
Styler.highlight_max
用样式突出显示最大值。
Styler.highlight_min
用样式突出显示最小值。
Styler.highlight_between
用样式突出显示定义的范围。
注意
该函数不适用于 str
数据类型。
示例
使用 axis=None
并对所有集合数据应用一个分位数
>>> df = pd.DataFrame(np.arange(10).reshape(2,5) + 1)
>>> df.style.highlight_quantile(axis=None, q_left=0.8, color="#fffd75")
...
或者按行或按列突出显示分位数,在这种情况下按行突出显示
>>> df.style.highlight_quantile(axis=1, q_left=0.8, color="#fffd75")
...
使用 props
而不是默认的背景颜色
>>> df.style.highlight_quantile(axis=None, q_left=0.2, q_right=0.8,
... props='font-weight:bold;color:#e83e8c')
pandas.io.formats.style.Styler.background_gradient
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.background_gradient.html
Styler.background_gradient(cmap='PuBu', low=0, high=0, axis=0, subset=None, text_color_threshold=0.408, vmin=None, vmax=None, gmap=None)
以渐变样式着色背景。
背景颜色根据每列、行或框架中的数据或给定的渐变映射确定。需要 matplotlib。
参数:
cmap字符串或颜色映射
Matplotlib 颜色映射。
low浮点数
在低端压缩颜色范围。这是数据范围的倍数,用于扩展到最小值之下;通常好的值在[0, 1]之间,默认为 0。
high浮点数
在高端压缩颜色范围。这是数据范围的倍数,用于扩展到最大值之上;通常好的值在[0, 1]之间,默认为 0。
axis,默认为 0
对每列应用(axis=0
或'index'
),对每行应用(axis=1
或'columns'
),或者一次对整个 DataFrame 应用axis=None
。
subset标签,类似数组,IndexSlice,可选
有效的 2d 输入为 DataFrame.loc[data
。
text_color_threshold浮点数或整数
用于确定文本颜色的亮度阈值在[0, 1]之间。有助于文本
在不同背景颜色下的可见性。如果为 0,则所有文本��是深色,如果为 1,则为浅色。
如果为 1,则为 light,默认为 0.408。
vmin浮点数,可选
对应于颜色映射最小值的最小数据值。如果未指定,则将使用数据(或 gmap)的最小值。
vmax浮点数,可选
对应于颜色映射最大值的最大数据值。如果未指定,则将使用数据(或 gmap)的最大值。
gmap类似数组,可选
渐变映射用于确定背景颜色。如果未提供,则将使用行、列或框架下的基础数据。如果作为一个 ndarray 或类似列表提供,必须与基础数据的形状相同,考虑axis
和subset
。如果作为 DataFrame 或 Series 提供,必须具有相同的索引和列标签,考虑axis
和subset
。如果提供了,vmin
和vmax
应相对于此渐变映射给出。
版本 1.3.0 中的新功能。
返回:
Styler
另请参阅
Styler.text_gradient
以渐变样式着色文本。
注意
当使用low
和high
时,渐变的范围,由数据给出(如果未给出 gmap)或由 gmap 给出,实际上在低端通过 map.min - low * map.range 扩展,高端通过 map.max + high * map.range 扩展,然后归一化和确定颜色。
如果与vmin
和vmax
结合使用,则 map.min、map.max 和 map.range 将被根据从vmin
和vmax
派生的值替换。
该方法将预先选择数值列,并忽略非数值列,除非提供了gmap
,在这种情况下不进行预先选择。
示例
>>> df = pd.DataFrame(columns=["City", "Temp (c)", "Rain (mm)", "Wind (m/s)"],
... data=[["Stockholm", 21.6, 5.0, 3.2],
... ["Oslo", 22.4, 13.3, 3.1],
... ["Copenhagen", 24.5, 0.0, 6.7]])
按列着色数值,使用axis=0
,预先选择数值列
>>> df.style.background_gradient(axis=0)
使用axis=None
集体着色所有值
>>> df.style.background_gradient(axis=None)
从low
和high
两端压缩颜色映射
>>> df.style.background_gradient(axis=None, low=0.75, high=1.0)
手动设置vmin
和vmax
梯度阈值
>>> df.style.background_gradient(axis=None, vmin=6.7, vmax=21.6)
设置一个gmap
并应用到所有列,使用另一个cmap
>>> df.style.background_gradient(axis=0, gmap=df['Temp (c)'], cmap='YlOrRd')
...
为数据框设置梯度图(即axis=None
),我们需要明确说明subset
以匹配gmap
的形状
>>> gmap = np.array([[1,2,3], [2,3,4], [3,4,5]])
>>> df.style.background_gradient(axis=None, gmap=gmap,
... cmap='YlOrRd', subset=['Temp (c)', 'Rain (mm)', 'Wind (m/s)']
... )
pandas.io.formats.style.Styler.text_gradient
原文:
pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.text_gradient.html
Styler.text_gradient(cmap='PuBu', low=0, high=0, axis=0, subset=None, vmin=None, vmax=None, gmap=None)
以渐变样式着色文本。
文本颜色根据每列、行或框架中的数据或给定的渐变映射确定。需要 matplotlib。
参数:
cmapstr 或者 colormap
Matplotlib colormap。
low浮点数
在低端压缩颜色范围。这是数据范围的倍数,用于扩展到最小值以下;通常在[0, 1]之间取好值,默认为 0。
high浮点数
在高端压缩颜色范围。这是数据范围的倍数,用于扩展到最大值以上;通常在[0, 1]之间取好值,默认为 0。
axis,默认 0
对每一列应用(axis=0
或者'index'
),对每一行应用(axis=1
或者'columns'
),或者一次性对整个 DataFrame 应用(axis=None
)。
subset标签,类似数组,IndexSlice,可选
有效的 2d 输入 DataFrame.loc[data
。
vmin浮点数,可选
对应于 colormap 最小值的最小数据值。如果未指定,将使用数据(或 gmap)的最小值。
vmax浮点数,可选
对应于 colormap 最大值的最大数据值。如果未指定,将使用数据(或 gmap)的最大值。
gmap类似数组,可选
用于确定文本颜色的渐变映射。如果未提供,将使用行、列或框架的基础数据。如果作为 ndarray 或类似列表提供,必须与基础数据的形状相同,考虑axis
和subset
。如果作为 DataFrame 或 Series 提供,必须具有相同的索引和列标签,考虑axis
和subset
。如果提供了vmin
和vmax
,应相对于此渐变映射给出。
新版本 1.3.0 中新增。
返回:
样式化器
另请参阅
Styler.background_gradient
以渐变样式着色背景。
注意
当使用low
和high
时,渐变范围由数据给出(如果未给出 gmap)或由 gmap 给出,在低端有效地扩展为 map.min - low * map.range,在高端为 map.max + high * map.range,然后归一化和确定颜色。
如果与vmin
���vmax
结合使用,map.min、map.max 和 map.range 将被根据从vmin
和vmax
派生的值替换。
该方法将预先选择数值列,并忽略非数值列,除非提供了gmap
,在这种情况下不会进行预先选择。
示例
>>> df = pd.DataFrame(columns=["City", "Temp (c)", "Rain (mm)", "Wind (m/s)"],
... data=[["Stockholm", 21.6, 5.0, 3.2],
... ["Oslo", 22.4, 13.3, 3.1],
... ["Copenhagen", 24.5, 0.0, 6.7]])
按列着色值,使用axis=0
,预先选择数值列
>>> df.style.text_gradient(axis=0)
使用axis=None
集体着色所有值
>>> df.style.text_gradient(axis=None)
从低
和高
两端压缩颜色映射
>>> df.style.text_gradient(axis=None, low=0.75, high=1.0)
手动设置vmin
和vmax
梯度阈值
>>> df.style.text_gradient(axis=None, vmin=6.7, vmax=21.6)
设置一个gmap
并应用到所有具有另一个cmap
的列
>>> df.style.text_gradient(axis=0, gmap=df['Temp (c)'], cmap='YlOrRd')
...
为一个数据框设置梯度映射(即axis=None
),我们需要明确说明subset
以匹配gmap
的形状
>>> gmap = np.array([[1,2,3], [2,3,4], [3,4,5]])
>>> df.style.text_gradient(axis=None, gmap=gmap,
... cmap='YlOrRd', subset=['Temp (c)', 'Rain (mm)', 'Wind (m/s)']
... )