python - 过滤具有不同 dtype 单元格的列
问题描述
我最近问了一个关于为数据框的特定列应用 select_dtypes 的问题。
我有这个数据框,它的列上有不同的 dtypes(在这种情况下是 str 和 int)。
df = pd.DataFrame([
[-1, 3, 0],
[5, 2, 1],
[-6, 3, 2],
[7, '<blank>', 3 ],
['<blank>', 2, 4],
['<blank>', '<blank', '<blank>']], columns='A B C'.split())
我想为字符串和整数创建不同的掩码。然后我将根据这些面具应用样式。
首先让我们定义一个函数来帮助我为不同的数据类型创建我的掩码。(感谢@jpp)
def filter_type(s, num=True):
s_new = pd.to_numeric(s, errors='coerce')
if num:
return s_new.notnull()
else:
return s_new.isnull()
那么我们的第一个掩码将是:
mask1 = filter_type(df['A'], num=False) # working and creating the bool values
第二个掩码将基于整数间隔:
mask2 = df['A'].between(7 , 0 , inclusive=False)
但是当我运行 mask2 时,它给了我错误:
TypeError:'>' not supported between instances of 'str' and 'int'
我该如何克服这个问题?
注意:我想应用的样式如下:
def highlight_col(x):
df=x.copy
mask1 = filter_type(df['A'], num=False)
mask2 = df['A'].between(7 , 0 , inclusive=False)
x.loc[mask1, ['A', 'B', 'C']] = 'background-color: ""'
x.loc[mask2, ['A', 'B', 'C']] = 'background-color: #7fbf7f'
解决方案
pd.DataFrame.loc
用于设置值。您需要pd.DataFrame.style
设置样式。此外,您可以使用try
/except
来识别数字比较何时失败。
这是一个最小的例子:
def styler(x):
res = []
for i in x:
try:
if 0 <= i <= 7:
res.append('background: red')
else:
res.append('')
except TypeError:
res.append('')
return res
res = df.style.apply(styler, axis = 1)
结果:
推荐阅读
- javascript - 在 angularjs 中捕获浏览器控制台错误并在弹出窗口中显示它们
- angular - 角度:材料更新到最新版本。未下载指定版本
- ruby-on-rails - 轨道意外 tINTEGER,期待 tSTRING_CONTENT
- json - 如何通过 Azure 中的 ARM 模板添加新的公共 IP 来更新(不覆盖)现有负载均衡器
- python - 如何通过python列表自动进行多个mongoDB查询
- android - 如何通过旋转、缩放和缩放在 android 的 AR 核心中播放视频?
- c# - 如何从 Box Collider2D 中获取随机点
- android - 使用 ScrollView 滚动图像
- php - 我的日期格式 12-2018 如何在 php 中获取月份名称?
- python - 数据集输入中具有 Keras 拟合和张量的 Tensorflow 导致列表索引超出范围