Pandas excel цвет ячейки

I need some help here. So i have something like this

import pandas as pd
path = '/Users/arronteb/Desktop/excel/ejemplo.xlsx'
xlsx = pd.ExcelFile(path)
df = pd.read_excel(xlsx,'Sheet1')
df['is_duplicated'] = df.duplicated('#CSR')
df_nodup = df.loc[df['is_duplicated'] == False]
df_nodup.to_excel('ejemplo.xlsx', encoding='utf-8')

So basically this program load the ejemplo.xlsx (ejemplo is example in Spanish, just the name of the file) into df (a DataFrame), then checks for duplicate values in a specific column​​. It deletes the duplicates and saves the file again. That part works correctly. The problem is that instead of removing duplicates, I need highlight the cells containing them with a different color, like yellow.

martineau's user avatar

martineau

118k25 gold badges164 silver badges293 bronze badges

asked Sep 2, 2016 at 19:28

Carlos Arronte Bello's user avatar

You can create a function to do the highlighting…

def highlight_cells():
    # provide your criteria for highlighting the cells here
    return ['background-color: yellow']

And then apply your highlighting function to your dataframe…

df.style.apply(highlight_cells)

answered Sep 2, 2016 at 19:34

Harrison's user avatar

6

I just had this same problem and I just solved it this week. My problem was not getting the includes to work properly to get the online code that I found working properly.

I am going to assume you mean change the background color not change the font color. If I am wrong clarify your request.

My solution is tied to a particular library. openpyxl

#### This import section is where my mistake was at
#### This works for me
import openpyxl    ### Excel files 
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font
from openpyxl.styles import Fill, Color
from openpyxl.styles import Style
from openpyxl.styles.colors import RED
from openpyxl.styles.colors import GREEN


str_xls_PathFileCurrent = str_xls_FileName
### Opens Excel Document
var_xls_FileOpen    = openpyxl.load_workbook(str_xls_PathFileCurrent) 
### Opens up the Excel worksheet 
var_xls_TabName     = var_xls_FileOpen.worksheets[0]                  
### Put the spreadsheet tab names into an array 
ary_xls_SheetNames  = var_xls_FileOpen.get_sheet_names()              
### Open the sheet in the file you working on 
var_xls_TabSheet    = var_xls_FileOpen.get_sheet_by_name(ary_xls_SheetNames[0])
xls_cell = var_xls_TabSheet['d10']

#### Changes the cell background color 
xls_cell.style = Style(fill=PatternFill(patternType='solid'
    , fgColor=Color('C4C4C4')))  ### Changes background color 

#### Changes the fonts (does not use style) 
xls_cell.font = xls_cell.font.copy(color  = 'FFFF0000') ### Works (Changes to red font text) 
xls_cell.font = xls_cell.font.copy(bold  = True) ### Works (Changes to bold font) 
xls_cell.font = xls_cell.font.copy(italic= True) ### Works (Changes to Italic Text) 
xls_cell.font = xls_cell.font.copy(size  =   34) ### Works (Changes Size) 

answered Sep 2, 2016 at 19:39

M T Head's user avatar

M T HeadM T Head

1,0359 silver badges12 bronze badges

1

Время прочтения: 6 мин.

В данном материале мы пройдемся по наиболее полезным функциям, которые нам предоставляет связка pandas и XlsxWriter для записи данных.

Для начала загружаем зависимости и создаём DataFrame:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
sales_df = pd.read_excel('https://github.com/chris1610/pbpython/blob/master/data/sample-salesv3.xlsx?raw=true')
sales_summary = sales_df.groupby(['name'])['ext price'].agg(['sum', 'mean']).reset_index()
sales_summary

Сохранение данных с использованием библиотеки XlsxWriter следует проводить одним из следующих образов:

1-й способ

sales_summary.to_excel('table.xlsx', engine='xlsxwriter', index=False)

2-й способ

with pd.ExcelWriter('table.xlsx', engine='xlsxwriter') as wb:
    sales_summary.to_excel(wb, sheet_name='Summary', index=False)

Используя первый способ данные просто сохраняются в файл table.xlsx с использованием движка XlsxWriter (требует, чтобы был установлен соответствующий пакет). В целом, когда нам не требуется применять форматирование, параметр engine можно и опустить.

Во втором случае, помимо того, что мы имеем возможность сохранить несколько DataFrame на одном или нескольких листах, так же возможно добавить ячейкам форматирование, вставить графики и специализированные таблицы.

Автофильтрация

Наиболее простой в реализации функцией форматирования будет добавления автофильтров. Для этого на соответствующем листе следует вызвать метод autofilter и указать диапазон применения фильтрования:

with pd.ExcelWriter('table.xlsx', engine='xlsxwriter') as wb:
    sales_summary.to_excel(wb, sheet_name='Sheet1', index=False)
    sheet = wb.sheets['Sheet1']
    sheet.autofilter('A1:C'+str(sales_summary.shape[0]))

Возможно применение и индексной нотации:

sheet.autofilter(0, 0, sales_summary.shape[0], 2)

(Более подробно о autofilter по ссылке )

По документации требуется указывать полностью диапазон ячеек, использующихся в автофильтре, но в реальности excel корректно применяет фильтр даже когда указан только диапазон колонок, что несколько упрощает работу. Например, как в следующем случае:

sheet.autofilter(0, 0, 0, 2)

Настройка размеров ячеек

Изначально XlsxWriter предоставляет нам инструменты для установки высоты и ширины как для целых строк и столбцов, так и для их диапазонов, с некоторой оговоркой.

Чтобы установить высоту одной строки следует использовать метод:

sheet.set_row(0, 20)

где 0 – индекс строки, 20 – высота строки.

Для установки высоты нескольких строк потребуется провести итерацию по всем нужным строкам, или же можно установить значение высоты строки по умолчанию для всего документа:

sheet.set_default_row(20)

Для установки ширины столбца есть такой метод:

sheet.set_column(0, 0, 30) # Установить ширину одного столбца A в 30
sheet.set_column(0, 2, 30) # Установить ширину столбцов A, B, C в 30
sheet.set_column('A:C', 30) # Установить ширину столбцов A, B, C в 30

Важно заметить, что хоть официальная документация и утверждает, что при настройке ширины столбцов не должно быть пересекающихся диапазонов, однако следующий код прекрасно работает:

with pd.ExcelWriter('table.xlsx', engine='xlsxwriter') as wb:
    sales_summary.to_excel(wb, sheet_name='Sheet1', index=False)
    sheet = wb.sheets['Sheet1']

    sheet.autofilter(0, 0, 0, 2)
    sheet.set_column('A:C', 30)
    sheet.set_column('B:B', 8)

Установка значения по умолчанию для ширины столбцов не предусмотрена автором библиотеки. Так же библиотека не предусматривает инструмента для определения автоматической ширины или высоты ячеек, приходится мириться с этим неудобством и искать похожие по функциям обходные решения на форумах (например, тут).

Форматирование текста

Форматирование текста, такое как изменение размера, шрифта, цвета и т.д. так же делается с использованием уже известных нам функций: set_column и set_row.

with pd.ExcelWriter('table.xlsx', engine='xlsxwriter') as wb:    
    sales_summary.to_excel(wb, sheet_name='Sheet1', index=False)
    sheet = wb.sheets['Sheet1']

    cell_format = wb.book.add_format()
    cell_format.set_bold()
    cell_format.set_font_color('red')
    sheet.set_row(1, 40, cell_format) # Установка стиля для строки 2 и высоты 40
    
    cell_format = wb.book.add_format()
    cell_format.set_bold()
    cell_format.set_font_color('green')
    sheet.set_column(2, 2, 20, cell_format) # Установка стиля для столбца C и ширины 20
    
    cell_format = wb.book.add_format()
    cell_format.set_bold()
    cell_format.set_font_color('blue')
    sheet.set_column('A:B', 20, cell_format) # Установка стиля для столбцов A и B и ширины 20

В результате получаем следующий файл:

Из таблицы виден важный факт:

стиль ячеек не может быть перезаписан. На строку с заголовками pandas уже применил форматирование, таким образов мы на него уже воздействовать никак не можем. Аналогично со строкой 2, ячейки которой по идее должны были окраситься в синий и зеленый цвета, однако этого не произошло.

Если есть сильное желание придать свой собственный формат строке с заголовками таблицы, то можно сделать так:

with pd.ExcelWriter('table.xlsx', engine='xlsxwriter') as wb:    
    sales_summary.to_excel(wb, sheet_name='Sheet1', index=False, header=False, startrow=1)
    sheet = wb.sheets['Sheet1']

    cell_format = wb.book.add_format()
    cell_format.set_font_color('purple')
    cell_format.set_bg_color('#AAAAAA')
    cell_format.set_font_size(18)  

    sheet.write_row(0, 0, sales_summary.columns, cell_format) # сразу пишем целую строку данных
    # аналогично
    #for col, name in enumerate(sales_summary.columns):
    #    sheet.write(0, col, name, cell_format)

Добавление графиков

Помимо чистых цифр, бывает полезно добавить в таблицу некоторую сопровождающую информацию, например графики. Они могут быть сгенерированы средствами Excel или же как обыкновенное сгенерированное изображение.

Добавление сгенерированного изображения максимально просто и понятно.

  1. Создаём изображение
  2. Сохраняем его как файл
  3. Указываем полный или относительный путь к файлу изображения, ячейку, в которую хотим поместить изображение и дополнительные опции, если нужно (например отступ от края ячейки, масштабирование ширины, высоты изображения и т.д.. Подробнее о списке опций по ссылке
    Пример добавления изображения в документ:
with pd.ExcelWriter('table.xlsx', engine='xlsxwriter') as wb:    
    sales_summary.to_excel(wb, sheet_name='Sheet1', index=False)
    sheet = wb.sheets['Sheet1']
    sheet.set_column('A:C', 12)

    plt.pie(sales_summary['sum'], labels=sales_summary['name'], radius=1.4)
    plt.savefig('pie.jpeg', dpi=200, bbox_inches='tight')
    sheet.insert_image('E2', 'pie.jpeg')

С другой стороны, для добавления графиков используется непосредственно средствами библиотеки XlsxWriter метод add_chart объекта типа worksheet, в параметрах которого можно указать тип графика (pie в данном случае). После этого нужно заполнить списки категорий и значений через метод add_series. Данный метод принимает ссылки в буквенной и в численной нотации.

Перед добавлением графика на лист, можно дополнительно отформатировать внешний вид легенды, добавить ещё данных на ту же область, добавить названия осей и т.д. Под конец необходимо добавить график на лист вызовом метода insert_chart. Более подробно о работе с графиками в XlsxWriter можно почитать по ссылке

with pd.ExcelWriter('table.xlsx', engine='xlsxwriter') as wb:    
    sales_summary.to_excel(wb, sheet_name='Sheet1', index=False)
    sheet = wb.sheets['Sheet1']
    sheet.set_column('A:C', 12)

    chart = wb.book.add_chart({'type': 'pie'})
    chart.add_series({
        'categories': '=Sheet1!$A$2:$A$'+str(sales_summary.shape[0]+1),
        'values':     '=Sheet1!$B$2:$B$'+str(sales_summary.shape[0]+1),
    })
    # Аналогично
    #chart.add_series({
    #    'categories': ['Sheet1', 1, 0, sales_summary.shape[0], 0],
    #    'values':     ['Sheet1', 1, 1, sales_summary.shape[0], 1],
    #})
    chart.set_legend({'position': 'bottom'})

    sheet.insert_chart('E2', chart, {
        'x_scale': 2, 'y_scale': 2
    })
    #Аналогично
    #sheet.insert_chart(1, 4, chart, {
    #    'x_scale': 1.5, 'y_scale': 2
    #})

Мы рассмотрели некоторые возможности, которые предоставляет нам связка библиотек Pandas и XlsxWriter. Их очень легко и удобно встраивать в собственные проекты. Использование средств, описанных в данной статье, не исчерпывают все возможности этих библиотек, но даже с этим скромным инструментарием в кармане, вы можете сделать ваши выгрузки намного более информативными и приятными глазу.

my requirement highlight the different of those cell to «yellow» and new rows added will be highlight in red colour in excel as a output.

load1 dataset

StudentID   Visit1      Visit 2     Visit 3     Visit 4
1           16-04-20    23-04-20    30-04-20    07-05-20
2           17-04-20    24-04-20    01-05-20    08-05-20
3           18-04-20    25-04-20    02-05-20    09-05-20
4           19-04-20    26-04-20    03-05-20    10-05-20
5           20-04-20    27-04-20    04-05-20    11-05-20
6           21-04-20    28-04-20    05-05-20    12-05-20
7           22-04-20    29-04-20    06-05-20    13-05-20
8           23-04-20    30-04-20    07-05-20    14-05-20

load2 table

StudentID   Visit1      Visit 2     Visit 3     Visit 4
1           16-04-20    23-04-20    30-04-20    07-05-20
2           17-04-20    24-04-20    01-05-20    08-05-20
3           18-04-20    25-09-20    02-05-20    09-05-20
4           19-04-20    26-04-20    03-06-20    10-05-20
5           20-04-20    27-04-20    04-05-20    11-05-20
6           21-04-20    28-04-20    05-05-20    12-06-20
7           22-04-20    29-08-20    06-05-20    13-05-20
8           23-04-20    30-04-20    07-05-20    14-05-20
9           15-05-20    16-05-20    17-05-20    18-05-20

Output. I am looking for the output in excel in the below format with colours hi-lighted.

enter image description here

I am new to this pandas, I was able to get the different difference at dataframe level. Not at the outputed excel where to format each cell and row with colours.Please help .

the below are the script i tried to get the difference.

import pandas as pd
import os
import numpy as np
colour1= pd.read_excel('pandas.xlsx',sheet_name='load1')
colour2= pd.read_excel('pandas.xlsx',sheet_name='load2')
colour_merge=colour1.merge(colour2,left_on='StudentID', right_on='StudentID',how='outer')
colour_merge['Visit1dif']= np.where(colour_merge['Visit1_x']==colour_merge['Visit1_y'],0,1)
colour_merge['Visit2dif']= np.where(colour_merge['Visit 2_x']==colour_merge['Visit 2_y'],0,1)
colour_merge['Visit3dif']= np.where(colour_merge['Visit 3_x']==colour_merge['Visit 3_y'],0,1)
colour_merge['Visit4dif']= np.where(colour_merge['Visit 4_x']==colour_merge['Visit 4_y'],0,1)
colour_merge[['StudentID','Visit1_x','Visit1_y','Visit1dif','Visit 2_x','Visit 2_y','Visit2dif','Visit 3_x','Visit 3_y','Visit3dif','Visit 4_x','Visit 4_y','Visit4dif']]

Содержание

  1. coloring cells in excel with pandas
  2. 2 Answers 2
  3. Linked
  4. Related
  5. Hot Network Questions
  6. Subscribe to RSS
  7. Coloring Cells in Pandas
  8. 4 Answers 4
  9. Создание информативных и красивых Excel документов. XlsxWriter и Pandas
  10. 02.12.2020 Виктор Алексеев, г. Воронеж
  11. WZBSocialScienceCenter/pandas-excel-styler
  12. Sign In Required
  13. Launching GitHub Desktop
  14. Launching GitHub Desktop
  15. Launching Xcode
  16. Launching Visual Studio Code
  17. Latest commit
  18. Git stats
  19. Files
  20. README.md
  21. About
  22. Pandas & Excel — Read, Write, Charts
  23. Installs and imports
  24. Read an Excel File
  25. Write
  26. Cells formats
  27. Highlight cells
  28. Add Charts

coloring cells in excel with pandas

I need some help here. So i have something like this

So basically this program load the ejemplo.xlsx (ejemplo is example in Spanish, just the name of the file) into df (a DataFrame ), then checks for duplicate values in a specific column​​. It deletes the duplicates and saves the file again. That part works correctly. The problem is that instead of removing duplicates, I need highlight the cells containing them with a different color, like yellow.

2 Answers 2

You can create a function to do the highlighting.

And then apply your highlighting function to your dataframe.

I just had this same problem and I just solved it this week. My problem was not getting the includes to work properly to get the online code that I found working properly.

I am going to assume you mean change the background color not change the font color. If I am wrong clarify your request.

My solution is tied to a particular library. openpyxl

Linked

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.20.43331

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Coloring Cells in Pandas

I am able to import data from an excel file using Pandas by using:

Now that I have all the data in xl as DataFrame. I would like to colour some cells in that data based on conditions defined in another function and export the same (with colour coding) to an Excel file.

Can someone tell me how should I go about this?

4 Answers 4

Pandas has a relatively new Styler feature where you can apply conditional formatting type manipulations to dataframes. http://pandas.pydata.org/pandas-docs/stable/style.html

You can use some of their built-in functions like background_gradient or bar to replicate excel-like features like conditional formatting and data bars. You can also format cells to display percentages, floats, ints, etc. without changing the original dataframe.

Here’s an example of the type of chart you can make using Styler (this is a nonsense chart but just meant to demonstrate features):

To harness the full functionality of Styler you should get comfortable with the Styler.apply() and Styler.applymap() APIs. These allow you to create custom functions and apply them to the table’s columns, rows or elements. For example, if I wanted to color a +ive cell green and a -ive cell red, I’d create a function

and call it on my Styler object, i.e., df.style.applymap(_color_red_or_green) .

With respect to exporting back to Excel, as far as I’m aware this is not supported in Styler yet so I’d probably go the xlsxwriter route if you NEED Excel for some reason. However, in my experience this is a great pure Python alternative, for example along with matplotlib charts and in emails/reports.

Источник

Создание информативных и красивых Excel документов. XlsxWriter и Pandas

02.12.2020 Виктор Алексеев, г. Воронеж

Время прочтения: 6 мин.

В данном материале мы пройдемся по наиболее полезным функциям, которые нам предоставляет связка pandas и XlsxWriter для записи данных.

Для начала загружаем зависимости и создаём DataFrame:

Сохранение данных с использованием библиотеки XlsxWriter следует проводить одним из следующих образов:

Используя первый способ данные просто сохраняются в файл table.xlsx с использованием движка XlsxWriter (требует, чтобы был установлен соответствующий пакет). В целом, когда нам не требуется применять форматирование, параметр engine можно и опустить.

Во втором случае, помимо того, что мы имеем возможность сохранить несколько DataFrame на одном или нескольких листах, так же возможно добавить ячейкам форматирование, вставить графики и специализированные таблицы.

Автофильтрация

Наиболее простой в реализации функцией форматирования будет добавления автофильтров. Для этого на соответствующем листе следует вызвать метод autofilter и указать диапазон применения фильтрования:

Возможно применение и индексной нотации:

(Более подробно о autofilter по ссылке )

По документации требуется указывать полностью диапазон ячеек, использующихся в автофильтре, но в реальности excel корректно применяет фильтр даже когда указан только диапазон колонок, что несколько упрощает работу. Например, как в следующем случае:

Настройка размеров ячеек

Изначально XlsxWriter предоставляет нам инструменты для установки высоты и ширины как для целых строк и столбцов, так и для их диапазонов, с некоторой оговоркой.

Чтобы установить высоту одной строки следует использовать метод:

где 0 – индекс строки, 20 – высота строки.

Для установки высоты нескольких строк потребуется провести итерацию по всем нужным строкам, или же можно установить значение высоты строки по умолчанию для всего документа:

Для установки ширины столбца есть такой метод:

Важно заметить, что хоть официальная документация и утверждает, что при настройке ширины столбцов не должно быть пересекающихся диапазонов, однако следующий код прекрасно работает:

Установка значения по умолчанию для ширины столбцов не предусмотрена автором библиотеки. Так же библиотека не предусматривает инструмента для определения автоматической ширины или высоты ячеек, приходится мириться с этим неудобством и искать похожие по функциям обходные решения на форумах (например, тут).

Форматирование текста

Форматирование текста, такое как изменение размера, шрифта, цвета и т.д. так же делается с использованием уже известных нам функций: set_column и set_row.

В результате получаем следующий файл:

Из таблицы виден важный факт:

стиль ячеек не может быть перезаписан. На строку с заголовками pandas уже применил форматирование, таким образов мы на него уже воздействовать никак не можем. Аналогично со строкой 2, ячейки которой по идее должны были окраситься в синий и зеленый цвета, однако этого не произошло.

Если есть сильное желание придать свой собственный формат строке с заголовками таблицы, то можно сделать так:

Добавление графиков

Помимо чистых цифр, бывает полезно добавить в таблицу некоторую сопровождающую информацию, например графики. Они могут быть сгенерированы средствами Excel или же как обыкновенное сгенерированное изображение.

Добавление сгенерированного изображения максимально просто и понятно.

  1. Создаём изображение
  2. Сохраняем его как файл
  3. Указываем полный или относительный путь к файлу изображения, ячейку, в которую хотим поместить изображение и дополнительные опции, если нужно (например отступ от края ячейки, масштабирование ширины, высоты изображения и т.д.. Подробнее о списке опций по ссылке
    Пример добавления изображения в документ:

С другой стороны, для добавления графиков используется непосредственно средствами библиотеки XlsxWriter метод add_chart объекта типа worksheet, в параметрах которого можно указать тип графика (pie в данном случае). После этого нужно заполнить списки категорий и значений через метод add_series. Данный метод принимает ссылки в буквенной и в численной нотации.

Перед добавлением графика на лист, можно дополнительно отформатировать внешний вид легенды, добавить ещё данных на ту же область, добавить названия осей и т.д. Под конец необходимо добавить график на лист вызовом метода insert_chart. Более подробно о работе с графиками в XlsxWriter можно почитать по ссылке

Мы рассмотрели некоторые возможности, которые предоставляет нам связка библиотек Pandas и XlsxWriter. Их очень легко и удобно встраивать в собственные проекты. Использование средств, описанных в данной статье, не исчерпывают все возможности этих библиотек, но даже с этим скромным инструментарием в кармане, вы можете сделать ваши выгрузки намного более информативными и приятными глазу.

Источник

WZBSocialScienceCenter/pandas-excel-styler

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Excel Styler for pandas

Styling individual cells in Excel output files created with Python’s Data Analysis Library pandas.

DEPRECATION NOTICE: A new feature for styling Excel output was introduced with pandas v0.20, so this extension here is only needed in case you’re using an older version of pandas or need to export to .xls files instead of .xlsx .

This small addition to pandas allows to specify styles for individual cells in Excel exports from pandas DataFrames, which is not possible with the existing API methods. With this you can for example highlight certain cells by specifying font styles, font colors or background patterns and colors.

Of course it is also possible to add things like conditional formatting and other advanced functions to Excel files with XlsxWriter (see also Improving Pandas’ Excel Output). However, sometimes it is necessary set styles like font or background colors on individual cells on the «Python side». In this scenario, XlsxWriter won’t work, since «XlsxWriter and Pandas provide very little support for formatting the output data from a dataframe apart from default formatting such as the header and index cells and any cells that contain dates of datetimes.» In this case, you’re better off with this tool, for example when you are running complicated data validation routines (which you probably don’t want to implement in VBA) and want to highlight the validation results by coloring individual cells in the output Excel sheets.

See examples.py for more examples and usage cases.

Styling the cells

The styling definitions of individiual cells can be done by creating a nested dictionary of style options for xlwt. The dictionary will be converted to «easyxf» directives by pandas so that <«font»: <«color»: «red»>> will become «font: color red;» . See the Python Excel Tutorial, page 28 for available options.

Colors in Excel

For an overview of possible colors, see the Python Excel Tutorial, page 33. But be aware that «Colours in Excel files are a confusing mess» (ibid.).

  • tested with pandas 0.24
    • only works with «xls» files via xlwt engine («xlsx» support via OpenPyXL is not yet available)
  • NumPy is required

About

Styling individual cells in Excel output files created with pandas.

Источник

Pandas & Excel — Read, Write, Charts

Pandas is an awesome tool when it comes to manipulates data with python. Pandas also have really cool function to handle Excels files. Thought this article I will explain how to read and writes files, highlight cells and how to add charts.

Installs and imports

Install these packages with pip

Read an Excel File

Reading an excel file and importing it in a pandas dataframe is as simple as :

A Dataframe is a 2-dimensional labeled data structure, it the main data structure used in pandas.

read_excel as a lot of arguments as you can see in the doc. Here are the mains ones :

  • io : The file to load
  • sheetname: use it to load specifics sheets of your Excel
  • header: Index of the row where the name of the columns can be found. By default, it’s the first one.
  • skiprows : number of rows to skip at the beginning of the file.
  • usecols: lists of columns you want to import. If None it will import all of them.

Write

To write your dataframe in an excel file

You can also write to a specific sheet

Cells formats

Let’s adapt the formats of the cell. We want to set “Numbers“ columns with two decimals, “Percentage” should be in percentage and have the “Date” set to this format “mm/dd/yyyy”.

Highlight cells

Change cells colors and background color based on a condition.

Add Charts

We can directly add graph through the code

Now let’s do a line plot, but instead of a string we are passing a list to values, which is more convenient to use.

There are 5 elements in the list :
— Sheet’s name as a string
— The first cell row
— The first cell column
— The last cell row
— The last cell column

/! indexes start at 0
Here [“Sheet 1”, 1, 1, 7, 1] will take values from B2 to B8 in Sheet 1.

You can create all your favorites charts: scatter plots, stacked bar charts, pie charts … See more here

Источник

What will we cover in this tutorial?

We will learn how you can dynamically format the cells in Excel to have a specific color based on the value of a function – all done from Python.

As an example we will color the cells of two columns depending on which is larger.

If the value in MA50 is larger than value in MA200 it will color green and red otherwise.

In this concrete example we will collect historical stock prices and calculate the Moving Averages of 50 and 200 days on the closing price. In a crossover way to utilize moving averages, you would send a buy-signal when the 50-day moving average crosses above the 200-day moving average and a sell-signal if the other way around.

Step 1: Collect the data from Yahoo! Finance using Pandas-datareader

A great library to use to collect financial data is the Pandas-datareader.

We will collect data from Yahoo! Finance. As an example we will use General Motors historical stock data.

This can be done as follows.

import pandas_datareader as pdr
import datetime as dt

start = dt.datetime(2019, 1, 1)
ticker = pdr.get_data_yahoo("GM", start)

This will result in a Pandas DataFrame with data similar to this.

                 High        Low       Open      Close      Volume  Adj Close
Date                                                                         
2019-01-02  33.810001  32.410000  32.849998  33.639999   7662300.0  31.893360
2019-01-03  33.680000  32.200001  33.340000  32.250000  11618300.0  30.575533
2019-01-04  33.570000  32.430000  32.799999  33.330002  10784000.0  31.599455
2019-01-07  34.970001  33.480000  33.709999  34.360001  10722300.0  32.575977
2019-01-08  35.680000  34.490002  35.000000  34.810001  10532900.0  33.002617

Step 2: Calculate the Moving Averages

The moving average can be calculated by applying the rolling() and mean() methods on the DataFrame.

The rolling() creates a window size which is the number of observations used for calculating the statistic.

To calculate the Moving Average of window size 50 will use the last 50 data points to calculate the mean. To be consistent with Yahoo! Finance way of calculate the value, they use the Close price.

import pandas_datareader as pdr
import datetime as dt
import xlsxwriter
import pandas as pd

start = dt.datetime(2019, 1, 1)
ticker = pdr.get_data_yahoo("GM", start)
ticker['MA50'] = ticker['Close'].rolling(50).mean()
ticker['MA200'] = ticker['Close'].rolling(200).mean()

Which will give a tail similar to this output.

                 High        Low       Open  ...  Adj Close     MA50     MA200
Date                                         ...                              
2020-12-14  42.540001  41.419998  42.490002  ...  41.619999  38.5632  29.03155
2020-12-15  42.160000  41.310001  41.990002  ...  41.660000  38.7772  29.08725
2020-12-16  41.869999  40.810001  41.790001  ...  41.419998  38.9976  29.13670
2020-12-17  42.029999  41.430000  41.709999  ...  42.029999  39.2058  29.19635
2020-12-18  42.042801  41.139999  42.020000  ...  41.389999  39.3894  29.25985

Where the Moving Averages are added to the DataFrame.

Step 3: Exporting to Excel using XlsxWriter

We will use the powerful XlsxWriter to create our Excel sheet.

You can write the DataFrame directly by using to_excel(…), but we want to do more than that. Hence, we use the XlsxWriter directly.

import pandas_datareader as pdr
import datetime as dt
import pandas as pd

start = dt.datetime(2019, 1, 1)
ticker = pdr.get_data_yahoo("GM", start)
ticker['MA50'] = ticker['Close'].rolling(50).mean()
ticker['MA200'] = ticker['Close'].rolling(200).mean()
# We only want the index as a date and not datetime object
ticker.index = ticker.index.date
# We skip the first 200 entries, as it they do not have the MA200
ticker = ticker.iloc[200:]
# We reverse the DataFrame to have newest first
ticker = ticker.iloc[::-1]
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('moving_average.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
ticker.to_excel(writer, sheet_name='Moving Averages')
# Remember to close the writer to write the Excel sheet
writer.close()

This will create an Excel sheet similar to this one.

Step 4: Adding formatting to the cells

This is a bit more complex as we need to do the magic here.

We first need to create a reference to the sheet (worksheet) we work on to access the functionality.

The first thing we do is to resize column A, such that it opens in the correct size to see the date. This is done by using set_column(…).

Then we create a format, which can be applied on Excel cells. This is how we color them. Hence, we create one for green cells and later one for red cells.

We insert them by using conditional_format(…), which a range of cells. This can be applied in different ways, we use the A1 notation.

The options parameter in conditional_format(…) must be a dictionary containing the parameters that describe the type and style of the conditional format. To see details of the format please refer to the manual.

import pandas_datareader as pdr
import datetime as dt
import pandas as pd

start = dt.datetime(2019, 1, 1)
ticker = pdr.get_data_yahoo("GM", start)
ticker['MA50'] = ticker['Close'].rolling(50).mean()
ticker['MA200'] = ticker['Close'].rolling(200).mean()
# We only want the index as a date and not datetime object
ticker.index = ticker.index.date
# We skip the first 200 entries, as it they do not have the MA200
ticker = ticker.iloc[200:]
# We reverse the DataFrame to have newest first
ticker = ticker.iloc[::-1]
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('moving_average.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
ticker.to_excel(writer, sheet_name='Moving Averages')
# Get the xlsxwriter objects from the dataframe writer object.
workbook = writer.book
worksheet = writer.sheets['Moving Averages']
# Resize the column A
worksheet.set_column("A:A", 12)
# Calculate the last row number (we insert first DataFrame row in row 2)
last_row = len(ticker) + 1
# Create a format for a green cell
cell_format_green = workbook.add_format()
cell_format_green.set_bg_color('green')
# Create a conditional formatted of type formula
worksheet.conditional_format('H2:I{}'.format(last_row), {'type':     'formula',
                                                         'criteria': '=$H2>=$I2',
                                                         'format':   cell_format_green})
# Create a format for a red cell
cell_format_red = workbook.add_format()
cell_format_red.set_bg_color('red')
# Create a conditional formatted of type formula
worksheet.conditional_format('H2:I{}'.format(last_row), {'type':     'formula',
                                                         'criteria': '=$H2<$I2',
                                                         'format':   cell_format_red})
# Remember to close the writer
writer.close()

This will result in the expected Excel sheet.

Step 5: Validating it works as expected

Now for the final test.

The colors should be updated dynamically. Let’s try to change the value and see what happens.

It does. If we change the value of H2 to 10, it turns the cells to red.

Python Circle

Do you know what the 5 key success factors every programmer must have?

How is it possible that some people become programmer so fast?

While others struggle for years and still fail.

Not only do they learn python 10 times faster they solve complex problems with ease.

What separates them from the rest?

I identified these 5 success factors that every programmer must have to succeed:

  1. Collaboration: sharing your work with others and receiving help with any questions or challenges you may have.
  2. Networking: the ability to connect with the right people and leverage their knowledge, experience, and resources.
  3. Support: receive feedback on your work and ask questions without feeling intimidated or judged.
  4. Accountability: stay motivated and accountable to your learning goals by surrounding yourself with others who are also committed to learning Python.
  5. Feedback from the instructor: receiving feedback and support from an instructor with years of experience in the field.

I know how important these success factors are for growth and progress in mastering Python.

That is why I want to make them available to anyone struggling to learn or who just wants to improve faster.

With the Python Circle community, you can take advantage of 5 key success factors every programmer must have.

Python Circle

Python Circle

Be part of something bigger and join the Python Circle community.

Понравилась статья? Поделить с друзьями:
  • Pandas excel удалить строки
  • Pandas excel объединить ячейки
  • Pandas excel добавить столбец
  • Pandas excel xlsx file not supported
  • Pandas excel read cell