How's the community? I'm trying to do something that in principle speaking without knowing should be very simple but honestly I can't find how, I see solutions but they are somewhat complex and I'm trying to find something very simple, I have a dataframe where some cells say "free" I want that if in the cell (always the same column) it says "free" it is colored green for example.
Basically this is my script:
from netmiko import ConnectHandler
from datetime import datetime
import re
from pathlib import Path
import os
import pandas as pd
hora = datetime.now()
dia = hora.strftime("%d-%m-%Y")
fecha = hora.strftime("%d-%m-%Y_%H-%M-%S")
ruta = Path("E:\Python\Visual Studio Code Proyects\M2M Real\Archivos\ROUTER - show interfaces description pipe include Gi0-3-4-3.txt")
ruta2 = Path("E:\Python\Visual Studio Code Proyects\M2M Real\Archivos\\")
with open(ruta, "r") as f:
lines = f.readlines()
with open(ruta, "w") as fw:
for line in lines:
if not re.match("-{5}|\s+|([A-Za-z0-9]+( [A-Za-z0-9]+)+)", line):
fw.write(line)
csv_name2 = f'{ruta2}\{ruta.stem}.csv'
df = pd.read_fwf(ruta)
df["Description"] = (df.iloc[:, 3:].fillna("").astype(str).apply(" ".join, axis=1).str.strip())
df = df.iloc[:, :4]
df = df.drop(columns = ["Status", "Protocol"])
df.Interface = df.Interface.str.extract('Gi0/3/4/3\.(\d+)')
df = df[df.Interface.notnull()].reset_index()
print(df)
df = df.drop(["index"], axis=1)
print(df)
df['Interface'] = df['Interface'].astype(int)
df = df.set_index('Interface').reindex(range(1,3580)).fillna('free').reset_index()
print(df)
df = df.to_csv(csv_name2, index=False, sep=";")
The source file looks like this:
Interface Status Protocol Description
Gi0/3/4/3 up up ENLACE A Router2
Gi0/3/4/3.401 up up Frontera Cliente A
Gi0/3/4/3.402 up up Frontera Cliente B
Gi0/3/4/3.403 up up Frontera Cliente C
and after being iterated and in a summarized way since it has 3500 lines it looks like this:
Interface Description
395 free
396 free
397 free
398 free
399 free
400 free
401 Frontera Cliente A
402 Frontera Cliente B
403 Frontera Cliente C
404 Frontera Cliente D
As I was telling you, I need it to iterate through the cells of the "description" column and if it matches "free" I paint it green.
From already thank you very much!
First of all you cannot colorize a .csv file as it is just text
To color the cells based on a condition you can use the method
.style.applymap()
to which you pass a function that validates the condition and returns a string with the style to applyI leave you here the documentation so that you can review it in more detail Style Pandas
Example:
and then you apply the style to your
dataframe
and export it, in this case to an excel file to be able to visualize the applied styleand the result is the following: