gpt4 book ai didi

python - 将属性(不是函数)传递给 python `pandas.DataFrame.style`

转载 作者:太空宇宙 更新时间:2023-11-03 10:48:12 24 4
gpt4 key购买 nike

我有一个包含值的 pandas.DataFrame,比如说:

df = pd.DataFrame(np.random.randn(5, 3), columns=['a', 'b', 'c'])

In [160]: df
Out[160]:
a b c
0 -0.316527 -0.721590 1.812285
1 -1.704653 -0.415888 -0.294740
2 -1.126637 0.032084 -1.344484
3 0.081789 -1.311954 1.941496
4 0.617405 0.114212 -0.763610

现在我已经编写了自己的颜色渐变函数,这样我就可以得到一个相同大小和形状的pd.DataFrame,但每个单元格都有颜色十六进制代码,说:

df_clrs = pd.DataFrame([
['#bc4700', '#dea380', '#bc4700'],
['#384f69', '#dea380', '#bc4700'],
['#dea380', '#bc4700', '#384f69'],
['#384f69', '#384f69', '#dea380'],
['#dea380', '#bc4700', '#384f69']],
columns=['a', 'b', 'c']
)

In [164]: df_clrs
Out[164]:
a b c
0 #bc4700 #dea380 #bc4700
1 #384f69 #dea380 #bc4700
2 #dea380 #bc4700 #384f69
3 #384f69 #384f69 #dea380
4 #dea380 #bc4700 #384f69

我假设我已经用文本颜色完成了这个,所以:

 df_fnts = pd.DataFrame([
['#f1f1f1','#f1f1f1','#000000'],
['#000000','#f1f1f1','#f1f1f1'],
['#000000','#f1f1f1','#000000'],
['#f1f1f1','#000000','#f1f1f1'],
['#000000','#000000','#f1f1f1']],
columns=['a', 'b' ,'c']
)

In [167]: df_fnts
Out[167]:
a b c
0 #f1f1f1 #f1f1f1 #000000
1 #000000 #f1f1f1 #f1f1f1
2 #000000 #f1f1f1 #000000
3 #f1f1f1 #000000 #f1f1f1
4 #000000 #000000 #f1f1f1

我的目标是公开 DatFrame.style 功能,如 these tutorials 中所示.

但是,教程中演示的所有函数都侧重于传递函数(使用 pd.DataFrame.style.applymap),但是,我已经创建了所有属性。

我尝试过的事情

因为在文档中看起来您需要为该值附加适当的属性,所以我创建了一个这样的函数:

def _apply_prop(df, prop):
return df.applymap(lambda x: prop + ':' + x)

# apply the color mapping
df.style.applymap(
_apply_prop(
df_clrs,
'background-color'
)
).to_excel('~/Desktop/background-colors.xlsx')

但是我得到一个TypeError

TypeError: the first argument must be callable

最佳答案

df (5x3) 和 df_clrs (4x3) 有不同的形状。假设您已更正该问题,请尝试以下操作:

def _apply_prop(_, style, prop):
return style.applymap(lambda x: prop + ':' + x)

df.style.apply(_apply_prop, axis=None, style=df_clrs, prop='background-color')

输出:

Styled data frame

一些注意事项:

  • 不要调用 style.applymap。它遍历单元格。使用 apply(..., axis=...)遍历列/行/表。无论您迭代什么,都返回一个具有相同形状的对象。
  • 您不在apply/applymap 中执行样式功能。您提供函数的名称及其参数
  • 样式函数的第一个参数始终是要设置样式的数据框。 apply/applymap 将数据框隐式传递给样式函数。您可以通过关键字传递额外的参数。

关于python - 将属性(不是函数)传递给 python `pandas.DataFrame.style`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57169268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com