There is a table shows as following, each cell of "Description" column contains multiple lines of description about the product. I want to change the first line in each cell font to bold and color in red, and then export the worksheet to a new file.
Product | Description |
---|---|
P1 | Line 1 Line 2 Line 3 |
P2 | Line 1 Line 2 Line 3 |
P3 | Line 1 Line 2 Line 3 |
import pandas as pd
df = pd.read_excel(fileLocation)
df.style.set_properties(subset=['Description'], **{'font-weight': 'bold', 'color': 'red'}).to_excel('newFile.xlsx', engine='openpyxl')
I am using Python and Pandas moudle. Above code segment bold and color all the lines in cell. Is there a way to only bold and color the first line in cell? Or is there any other moudle can help with?
CodePudding user response:
Use:
df['Description'] = df['Description'].str.split('\n')
df1 = df.explode('Description')
df1['r'] = range(len(df1))
df1 = df1.set_index(['Product', 'r'])
def coloring(x):
c1 = 'color: red'
c = ''
mask1 = x['Description'] == 'Line 1'
df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
df1.loc[mask1, 'Description'] = c1
return df1
df1 = df1.style.apply(coloring, axis=None)
Output: