每次列值更改时在 pandas 数据框中绘制实线
Drawing solid line in pandas dataframe every time column value changes
每当“product_basket”列中的值重置时,我想在 pandas 数据框中画一条实线。
这是我的 df 的样子:
我想要的是:
请随时提出其他想法以获得类似的结果。
提前致谢,
斯特凡诺
您可以像这样使用移位和布尔运算找到组最后一行的索引
代码:
df = pd.DataFrame({"product_basket":["CAT","CAT","CAT","CAT","FUR","FUR","FUR","FUR","HYG","HYG"]})
df['last_of_group'] = (df['product_basket'].shift() != df['product_basket']).shift(-1).fillna(False)
print(df)
输出:
product_basket last_of_group
0 CAT False
1 CAT False
2 CAT False
3 CAT True
4 FUR False
5 FUR False
6 FUR False
7 FUR True
8 HYG False
9 HYG False
然后您可以对这些行进行格式化。
您可以先获取 product_basket
与下一个不相同的索引,然后为索引匹配的行应用 border-bottom
CSS 样式:
# `different` is a boolean series, we get the indices where it is True
different = df.product_basket.ne(df.product_basket.shift(-1))
inds = different[different].index
# for each row, `row.name` gives the index and if the condition is OK,
# we return a styling for the entire row with `len(row)`; else None
df.style.apply(lambda row: ["border-bottom: 2px solid blue;"]*len(row)
if row.name in inds
else [""]*len(row), axis=1)
带有一些示例数据
每当“product_basket”列中的值重置时,我想在 pandas 数据框中画一条实线。
这是我的 df 的样子:
我想要的是:
请随时提出其他想法以获得类似的结果。
提前致谢,
斯特凡诺
您可以像这样使用移位和布尔运算找到组最后一行的索引
代码:
df = pd.DataFrame({"product_basket":["CAT","CAT","CAT","CAT","FUR","FUR","FUR","FUR","HYG","HYG"]})
df['last_of_group'] = (df['product_basket'].shift() != df['product_basket']).shift(-1).fillna(False)
print(df)
输出:
product_basket last_of_group
0 CAT False
1 CAT False
2 CAT False
3 CAT True
4 FUR False
5 FUR False
6 FUR False
7 FUR True
8 HYG False
9 HYG False
然后您可以对这些行进行格式化。
您可以先获取 product_basket
与下一个不相同的索引,然后为索引匹配的行应用 border-bottom
CSS 样式:
# `different` is a boolean series, we get the indices where it is True
different = df.product_basket.ne(df.product_basket.shift(-1))
inds = different[different].index
# for each row, `row.name` gives the index and if the condition is OK,
# we return a styling for the entire row with `len(row)`; else None
df.style.apply(lambda row: ["border-bottom: 2px solid blue;"]*len(row)
if row.name in inds
else [""]*len(row), axis=1)
带有一些示例数据