Python is in Excel! – Here is a complete getting started guide for you

Share

Facebook
Twitter
LinkedIn

Recently Microsoft announced Python support for Excel. This is a BIG news for everyone using Excel to analyze data or find insights. In this article, let me give you a proper introduction to the Python in Excel feature and how to use it. 

If you prefer video, check out my Excel for Python is here video.

Introduction to Python in Excel

What is Python for Excel feature?

When you have "python in excel" it will show up in Formula ribbon

You can now write Python code natively in Excel cells and return the output as either Python objects or Excel values. For example, you want to perform quick statistical analysis of your sales data in the range A1:D10. You can use the below Python code to do this now.

=XL(“A1:D10”, headers=True).describe()

How do I enable Python for Excel?

This “preview” feature is only available with Excel 365 beta users as of September 2023.

If you have Excel 365, you can go to File > Account to enable “insider” program. More details on eligibility and instructions are here – https://insider.microsoft365.com/en-us/join/windows

After you’ve joined the program, update your Office from File > Account page.

Office update may be needed to get python in Excel

After the update, if you have Python for Excel, it will show up in the formula ribbon, as depicted below.

If you don’t have it yet, just wait a few weeks. It will show up eventually.

When you have "python in excel" it will show up in Formula ribbon

How to use Python in Excel:
A Quick Tutorial

Open Excel and load any of your data files. Alternatively, if you need sample data, copy paste the below table into Excel.

Sales Person Product Country Date Sales Boxes
Gigi Bohling Manuka Honey Choco India 20-Jul-23 8162 742
Barr Faughny White Choc Canada 16-Aug-23 2485 355
Marney O’Breen Peanut Butter Cubes India 14-Jul-23 10255 733
Wilone O’Kielt Mint Chip Choco India 2-Jul-23 16800 800
Gunar Cockshoot Orange Choco New Zealand 2-Aug-23 2842 203
Andria Kimpton Baker’s Choco Chips Canada 18-Jul-23 9373 427
Beverie Moffet Fruit & Nut Bars India 14-Jul-23 6573 598
Mallorie Waber Baker’s Choco Chips India 24-Jul-23 3598 150
Barr Faughny Spicy Special Slims Canada 11-Jul-23 5138 571
Dennison Crosswaite White Choc Canada 22-Jul-23 1547 258
Ches Bonnell 99% Dark & Pure New Zealand 16-Aug-23 12901 993
Andria Kimpton Organic Choco Syrup USA 16-Jul-23 7161 651
Gunar Cockshoot Fruit & Nut Bars New Zealand 19-Jul-23 11935 1492
Beverie Moffet After Nines India 18-Aug-23 5089 268
Gunar Cockshoot Peanut Butter Cubes USA 11-Jul-23 9247 578
Andria Kimpton Peanut Butter Cubes India 22-Jul-23 10731 826
Gigi Bohling After Nines Australia 4-Jul-23 9730 609
Gunar Cockshoot Eclairs USA 1-Aug-23 3150 287
Karlen McCaffrey 99% Dark & Pure USA 6-Aug-23 2247 205
Roddy Speechley Peanut Butter Cubes USA 1-Jul-23 2765 213
Brien Boise Caramel Stuffed Bars India 3-Aug-23 7112 647
Wilone O’Kielt Organic Choco Syrup UK 27-Aug-23 3787 345
Dennison Crosswaite Peanut Butter Cubes Canada 29-Aug-23 2674 168
Gigi Bohling White Choc India 14-Aug-23 378 54
Karlen McCaffrey Raspberry Choco Australia 7-Jul-23 7217 401
Marney O’Breen Spicy Special Slims New Zealand 19-Aug-23 735 147
Mallorie Waber Organic Choco Syrup UK 3-Jul-23 4690 427
Karlen McCaffrey Manuka Honey Choco India 24-Jul-23 8008 572
Wilone O’Kielt Spicy Special Slims Australia 18-Jul-23 12586 2518
  1. Once you have some data in Excel, press CTRL ALT SHIFT P to enable Python mode. If you get a “welcome to Python screen” complete the tour and then press the shortcut again.
  2. Using your mouse or keyboard, select the data in your workbook. Excel should write the necessary XL() command to capture your data into Python as a dataframe.
  3. To see the dataframe you just built, press CTRL Enter. Excel will display a “Python Object” in the cell.

DATAFRAME: a dataframe is a python concept for storing data. They are like Excel tables. Each column of dataframe has one kind of data.

How to create a dataframe in Excel Python

To see the output as values
instead of Python object

converting python output to Excel values

You can see the “actual” values of your Python code anytime. Just select the cell with Python output and either press CTRL+ALT+SHIFT+M or right click on the cell and choose “Python Output” > Excel values option.

10 Python Coding Examples

Use these code samples to play with Python in Excel. Before starting.

  • Copy the above table of sample data and paste it in Excel (in range A1:F30). Alternatively, download this file with the data.
  • To type the code, enter python mode (CTRL ALT SHIFT P) or use the formula =PY( in a cell.

Example 0

Construct dataframe 👩‍💻

df = xl("A1:F30", headers=True)

 

Explanation & Output 💻

This will just create a dataframe named df and return that to the cell. You can either leave it or see the underlying data (which will be same as A1:F30) by changing the output style.

Example 1

Description of the data 👩‍💻

df.describe()

 

Explanation & Output 💻

This will generate a dataframe with statistical descriptions for all your number columns. Example output is shown below.

dataframe describe - sample output

Example 2

Description of the data, all columns 👩‍💻

df.describe(include="all")

 

Explanation & Output 💻

This will generate a dataframe with statistical descriptions for all your columns. Perfect for situations when you have some text, dates and numbers in your data. Sample output shown below:

dataframe description for all columns

Example 3

Unique Product Names 👩‍💻

df["Product"].unique()

 

Explanation & Output 💻

This will generate a python array (ndarray) that has all the product names with duplicate values removed.

Example 4

Add “Sales per Box” calculated column to the dataframe 👩‍💻

df["sales per box"]=df["Sales"]/df["Boxes"]

 

Explanation & Output 💻

This will add a new column [“sales per box”] to the dataframe with the calculation logic: sales divided by boxes. You can use the same approach to add many other columns

Example 5

Add “Sales as percentage” calculated column to the dataframe 👩‍💻

total_sales = sum(df.Sales)
df["Sales as a percentage"] = df["Sales"]/total_sales
df

 

Explanation & Output 💻

First, we calculate the “total_sales” and keep it in a variable. Then we use that variable to calculate the sales as a percentage.

💡 TIP: Do you notice the different ways in which you can refer dataframe columns? You can use dot notation (ex: df.Sales) or bracket notation (ex: df[“Sales”])

HOMEWORK PROBLEMS

Can you add below columns to the df dataframe?

  • Sales value rounded to nearest thousand.
  • Month number of the sales date
  • Flag each record as “Canada” or “Non-Canada”

Example 6

Group Sales by Date and Show a Pivot 👩‍💻

df.groupby(by="Date").sum()

Explanation & Output 💻

This creates a default groupby (similar to pivot in Excel) of your data by showing totals by date. This will sum() all the number columns in your dataframe. See the below sample output.

groupby operation and output in Python (for Excel)

Example 7

Group Sales by Date but only show Sales & Boxes columns 👩‍💻

df.groupby("Date")[["Sales", "Boxes"]].sum() 

Explanation & Output 💻

This creates a customized groupby with Sales & Boxes columns totals by Date. Use this pattern when you don’t want to summarize certain things (like Sales per box).

Example 8

Create a bar graph with Daily Sales 👩‍💻

import matplotlib.pyplot as plt
plt.bar(df["Date"], df["Sales"])

 

Explanation & Output 💻

We import the plotting library matplotlib.pyplot and use that to generate a bar graph with default settings.

Sample output is shown below:

 

Example 9

Create a bar graph with Daily Sales – another method 👩‍💻

df_groups = df.groupby("Date")["Sales"].sum()
df_groups.plot(kind="bar")

 

Explanation & Output 💻

This code uses the built-in plotting function of the pandas library to generate the bar graph. Notice how this doesn’t show missing dates.

Sample output is shown below:

Example 10

Filter the dataframe to show all records where the product has the word “Choc” 👩‍💻

df[df["Product"].str.contains("Choc")] 

Explanation & Output 💻

This code generates a new dataframe that contains all rows where the Product column has the word “Choc” in it.

MORE HOMEWORK PROBLEMS

  • Can you filter all the records that have either “Choc” or “choc”?
  • Create a bar graph of this data to show total sales by each product

How does Python in Excel work?

You need internet connection to run Python code in Excel. All the code you write is executed in Microsoft Cloud. This also means your data travels on the network to Microsoft Cloud and returns with the result.

What happens if your code has an error?

 

python error panel - excel

If there is an error in your Excel Python code, you will see a new error message #PYTHON! in Excel.

You will also see #BUSY! when Excel is running your Python code (in Microsoft Cloud).

In case of an error in your code, Excel automatically opens the Python Diagnostics tab and displays more information there.

Execution order of your code

The python code you write in Excel will run in row-major order. This means, the code runs row by row, left to right. See this illustration to understand the process.

Resources to Learn Python 🐍

Now that you are familiar with Python in Excel, you may want to learn more. May I suggest using the below approach.

  1. See if you can enable use Python in Excel to get a feel of the technology.
  2. Install a proper Python IDE like Anaconda, VS Code or something else to learn & practice Python properly.
  3. Understand the Python programming concepts like variables, conditions, list comprehension, dataframes and EDA. Here is a good article on the process.
  4. Apply these concepts on your own / business data to solidify your understanding.
  5. If you need practice datasets, try Kaggle.

📺 Python Videos

📚 Python Books

This is the book we all (Jo, kids & I) read and really loved it. The explanations and examples are easy enough to get started. There is enough variety to please everyone. 

More practical if you want to get things done with Python. I read it a few times and really like the practicality of the book.

Python is particularly useful for doing data science & building machine learning models. This is an area of focus for me in the next months. I suggest getting the Python Data Science book once you have strong foundation in the language.

Note: I am using affiliate link for these books. 

💻 Microsoft Resources

As part of the Python for Excel launch, Microsoft also added many resources and example pages to their website. Check out these pages.

Facebook
Twitter
LinkedIn

Share this tip with your colleagues

Excel and Power BI tips - Chandoo.org Newsletter

Get FREE Excel + Power BI Tips

Simple, fun and useful emails, once per week.

Learn & be awesome.

Welcome to Chandoo.org

Thank you so much for visiting. My aim is to make you awesome in Excel & Power BI. I do this by sharing videos, tips, examples and downloads on this website. There are more than 1,000 pages with all things Excel, Power BI, Dashboards & VBA here. Go ahead and spend few minutes to be AWESOME.

Read my storyFREE Excel tips book

Overall I learned a lot and I thought you did a great job of explaining how to do things. This will definitely elevate my reporting in the future.
Rebekah S
Reporting Analyst
Excel formula list - 100+ examples and howto guide for you

From simple to complex, there is a formula for every occasion. Check out the list now.

Calendars, invoices, trackers and much more. All free, fun and fantastic.

Advanced Pivot Table tricks

Power Query, Data model, DAX, Filters, Slicers, Conditional formats and beautiful charts. It's all here.

Still on fence about Power BI? In this getting started guide, learn what is Power BI, how to get it and how to create your first report from scratch.

38 Responses to “Time to showoff your VBA skills – Help me fix ActiveSheet.Pictures.Insert snafu”

  1. shokks says:

    I tried your code with 2003, it works.

    But, I know Addpicture does not take URLs anymore with 2007 onwards, perhaps its the same with picture.insert as well.

    http://support.microsoft.com/kb/928983/en-us

    The above link gives the solution as "picture fill in a shape such as a rectangle".

  2. Vince E. says:

    Tried to recreate this, but it worked fine for me. I just took the image of the error you showed in the post. Is there more info that can narrow this down a bit?

  3. Ian Hinckley says:

    Hi

    Not sure if this is what you're after, but I just tried this

    Sub Macro1()
    ActiveSheet.Pictures.Insert("http://www.google.co.uk/intl/en_uk/images/logo.gif").Select
    End Sub

    Tied a button to it on the sheet and it seems to work; hope this helps a little

    Ian

  4. Chandoo says:

    @All.. the issue is in Excel 2007. In 2003 ActiveSheet.Pictures.Insert seems to work fine. Unfortunately, I have design this in Excel 2007.. that is why I posted it here..

  5. Ian Hinckley says:

    v2

    Sub Macro1()
    Set n = ActiveSheet.Pictures.Insert("http://www.google.co.uk/intl/en_uk/images/logo.gif")
    With Range("c12")
    t = .Top
    l = .Left
    End With
    With n
    .Top = t
    .Left = l
    End With
    End Sub

    Ian

  6. Ian Hinckley says:

    That didn't come out very well. This positions at c12, so can change easily:
    Sub Macro1()
    Set n = ActiveSheet.Pictures.Insert("http://www.google.co.uk/intl/en_uk/images/logo.gif")
    With Range("c12")
    t = .Top
    l = .Left
    End With
    With n
    .Top = t
    .Left = l
    End With
    End Sub

    Works OK in 2007

    Ian

  7. Chandoo:
    Try 'ActiveSheet.Pictures.Insert'

    With ActiveSheet.Pictures.Insert("C:\Example.png")
    .Left = ActiveSheet.Range("A1").Left
    .Top = ActiveSheet.Range("A1").Top
    End With

  8. Jon Peltier says:

    activesheet.pictures.insert "C:\Documents and Settings\Jon Peltier\Desktop\2007 stuff\insert_charts_2007.png"

    Works for me in 2003 SP3 and in 2007 SP2.

    Check the URL, and make sure you have internet connectivity.

    What also works, and is newer (pictures.insert was supposedly deprecated in '97):

    activesheet.shapes.addpicture "C:\Documents and Settings\Jon Peltier\Desktop\2007 stuff\insert_charts_2007.png", false, true, 200,200,100,100

    Unfortunately you must specify dimensions (the last four arguments) and you don't necessarily know them. But the picture size is still related back to the original picture size, so you could use scaleheight and scalewidth to fix this.

  9. Chandoo: I just re-read your post.

    The code I posted works for me. However, I'm using a local picture. If you try to add a picture from the web, this won't work.

    I remember solving this problem before by adding a rectangle shape first, then using the Shapes.AddPicture method to get a picture from the web.

    I'll find that code and post it here.

  10. Chandoo says:

    Some more updates... The code "ActiveSheet.Pictures.Insert (path)" works fine in Excel 2007 at home. Strange it failed miserably on my work laptop. Do you think this has got something to do with SP2 of MS Office 2007 or something like that?

    @Ian, Jon: Thanks for the code snippets. I guess I will use my home installation of excel to do this.

  11. Chandoo:

    Try this on your work laptop:

    Sub test()
    ActiveSheet.Shapes.AddShape msoShapeRectangle, 50, 50, 100, 200
    ActiveSheet.Shapes(1).Fill.UserPicture _
    "http://www.datapigtechnologies.com/images/dpwithPig6.png"
    End Sub

  12. Jon Peltier says:

    I didn't mean to post code with a local file, because both approaches worked with an internet image as well. This is in Excel 2007 SP2.

    activesheet.pictures.insert "http://peltiertech.com/images/2009-07/col_area_noblanks.png"

  13. Jon: Looks like I have SP1 on my client machine! I wasn't paying attention.

    Just checked my home computer where I have SP2, and you're right...looks like they fixed it.

  14. Jon Peltier says:

    I didn't even bother testing in SP1, though I could if anyone cares enough.

  15. teylyn says:

    I'm afraid I don't have a solution, but I find it remarkable that after attaining a certain status in the Excel world, Chandoo does not need to post on an Excel discussion forum to get help for an Excel problem. Instead, he posts on his blog and all the gurus come rushing to his help.

    Isn't Web 2.0 great?

  16. Jon Peltier says:

    Teylyn - I saw Chandoo's tweet first, and followed the link back to his blog.

  17. Chandoo says:

    @Mike.. thank you. I have seen the fill rectangle solution before posting the query here. For that matter, I have also tried the solution of embedding a browser control on a spreadsheet. both of these seemed a bit extreme. That is why I have asked it here.

    But I guess I will end up using it if I had to build this in work laptop.

    @Teylyn: I have thought of posting this in a forum. (Unfortunately I have not been to any excel group in the last 5 years. Last time I was active was when I built a jave based excel sheet construction solution using POI.HSSF classes of Apache... ) After searching for a few hours, I found several forum posts where others had same problem and the solution recommended (using .left and .top parameters) is not working for me. Incidentally most of these solutions are from a certain Jon Peltier 😛

    I thought may be the problem is interesting for fellow blog readers. So I posted it here.

  18. Justin B says:

    Hi,
    Adapting the code in the question,

    [code]
    Sub InsPicture()
    pPath = "http://chandoo.org/images/pointy-haired-dilbert-excel-charts-tips.png"
    With ActiveSheet.Pictures.Insert(pPath)
    .Left = Range("a1").Left
    .Top = Range("a1").Top
    End With
    End Sub
    [/code]

    Seems to work fine

  19. Jon Peltier says:

    Looks like it was a problem in 2007 up to SP1, which was corrected in SP2.

  20. Chandoo says:

    @Jon.. seems like the case. I just checked the version at work laptop. it is 12.0.6331.5000 (SP1).

    Thank you so much every one. I really appreciate your time and suggestions in solving this.

  21. Jon Peltier says:

    Glad to help. I couldn't understand why something so straightforward wasn't working.

  22. Kieranz says:

    Hi All
    Is there a way of inserting a motion clip eg animated gif or swf or flv?
    Thks

    • Chandoo says:

      You can insert animated GIFs by inserting them in a browser control through VBA. For other types of movies, I can guess you can insert them as clip art.

  23. ashvini says:

    I WANT THE INSERT PICTURE BY USING COADING

  24. Lutz says:

    so currently i was struggling same as you, chandoo, with the insert picture method in excel 2007/10 from an url and came along your thread here.

    so i re-designed the code on the addshape method as mike was suggesting it and all of the sudden it works just fine.

    thanks alot to you guys, you were a great help
    a big salut from switzerland

  25. Santiago says:

    Hi guys,

    I need help copying and pasting an image with the path in a cell.
    I leave the code.

    And thank you very much!

    Sub Copiarimg()

    Dim pic As Picture

    With ActiveSheet

    Set pic = .Pictures.Insert(Range("f2").Value)

    With .Range("e9:g22")
    pic.Top = .Top
    pic.Left = .Left
    pic.Width = .Width
    pic.Height = .Height
    End With
    End Sub

  26. I've played around with the approaches in these comments, and the code below is what I've come up with. The ImagePath can be a local file or a URL. As Jon mentioned above, the trick is to set an arbitrary value for the width and height, then call the ScaleWidth and ScaleHeight methods afterward to reset the picture to its original size. Once the LockAspectRatio property is set, you can change the picture width and the height will automatically scale (or vice-versa).

    Sub AddPictureToRange(TopLeftCellAddress As String, ImagePath As String)

    Dim pic As Shape
    Dim l As Single, t As Single
    Dim temp As Single

    l = Me.Range(TopLeftCellAddress).Left
    t = Me.Range(TopLeftCellAddress).Top
    temp = 10# ' arbitrary value

    Set pic = Me.Shapes.AddPicture(ImagePath, msoFalse, msoTrue, l, t, temp, temp)
    pic.ScaleHeight 1#, msoTrue
    pic.ScaleWidth 1#, msoTrue
    pic.LockAspectRatio = msoTrue

    End Sub

  27. dip says:

    I need some help with inserting pictures. I have an excel file with a column of item numbers next to this row I want to insert a picture of this item. The pictures are coded with the item number so I tried to insert it with one of the codes above:

    Sub InsPicture()
    pPath = "http://img.bricklink.com/P/80/55236.gif"
    With ActiveSheet.Pictures.Insert(pPath)
    End With
    End Sub

    That worked but I need to do that for every row separtly.
    So I tried in the code
    pPath = "http://img.bricklink.com/P/80/"&Text(a1;"#")&".gif"

    But that gives errors.

    Anybody ideas?

  28. alex says:

    Hi Nicholas, I used your solution in a related problem in Excel 2003 and it worked flawlessly..thank you!

  29. Richard says:

    Hi Mike Alexander,

    Your solution with some changes was helpful in my problem in XL 2007, thanks.

  30. seejay says:

    Hi,

    thanks all. In addition, I had a problem with multiple pictures inserting (every new picture replaced the prior one). I've changed it a bit, may be helpful..

    Sub test()
    ActiveSheet.Shapes.AddShape msoShapeRectangle, 50 , 50, 100, 200
    ActiveSheet.Shapes(1).Fill.UserPicture _
    "http://www.datapigtechnologies.com/images/dpwithPig6.png"
    ActiveSheet.Shapes(1).Copy
    ActiveSheet.Paste
    End Sub

  31. Jon Peltier says:

    Try this instead:
     
    Sub test()
    ActiveSheet.Shapes.AddShape msoShapeRectangle, 50 , 50, 100, 200
    ActiveSheet.Shapes(ActiveSheet.Shapes.Count).Fill.UserPicture _
    "http://www.datapigtechnologies.com/images/dpwithPig6.png"
    End Sub

    • Kez says:

      Thanks to everyone, this thread has been very helpful. However, image inserting still doesn't work quite as expect for me.

      While I can get a picture inserted into an Excel 2010 worksheet using either:

      1) ActiveSheet.Shapes(ActiveSheet.Shapes.Count).Fill.UserPicture...
      2) ActiveSheet.Pictures.Insert(pPath), and
      3) Shapes.AddPicture...

      unfortunately the images all insert with a display size determined not by the actual pixel dimensions of the image but by the dpi resolution.

      So for example, if I insert two copies of the exact same 600x600 pixel image, one with a 300dpi resolution and the other with 72dpi, they display at vastly different sizes on screen.

      While this might be intended behaviour for Excel in order to maintain a WSYWIG printing layout, I actually need a way to insert the image based on the the actual pixel dimesnsions and ignoring the dpi resolution.

      Any help appreciated.

      Thanks
      Kez

  32. Kez says:

    Not doing an intentional bump, but realised I posted in rely to one of the repsonses here instead of to the main thread, so reposting.
    =====

    Thanks to everyone, this thread has been very helpful. However, image inserting still doesn’t work quite as expected for me.

    While I can get a picture inserted into an Excel 2010 worksheet using any of the below methods:

    1) ActiveSheet.Shapes(ActiveSheet.Shapes.Count).Fill.UserPicture....
    2) ActiveSheet.Pictures.Insert(pPath), and
    3) Shapes.AddPicture....

    unfortunately the images all insert with a display size determined not by the actual pixel dimensions of the image but by the dpi resolution.

    So for example, if I insert two copies of the exact same 600×600 pixel image, one with a 300dpi resolution and the other with 72dpi, they display at vastly different sizes in Excel on screen.

    While this might be intended behaviour for Excel in order to maintain a WYSIWYG printing layout, I actually need a way to insert the images based on the the actual pixel dimesnsions and ignoring the dpi resolution.

    Any help appreciated.

    Thanks
    Kez

  33. Kez says:

    Well, answered my own question 🙂

    For those who might be interested, you can use this function:

    Public Function GetPicDims(strFilePath As String, strFileName As String) As String
    GetPicDims = CreateObject("Shell.Application").Namespace((strFilePath)). _
    ParseName(strFileName).ExtendedProperty("Dimensions")
    End Function

    to get the dimensions of the image you want to insert. Then you can parse the return string and use the width and height values to add a rectangle shape of the appropraite size, like:

    ActiveSheet.Shapes.AddShape msoShapeRectangle 50, 50, iWidth, iHeight

    which you then fill with the picture:

    ActiveSheet.Shapes(ActiveSheet.Shapes.Count).Fill.UserPicture "c:\temp\test.jpg"

    This way the picture gets inserted using the pixel dimensions and the (print) resolution gets ignored.

    If desired, the GetPicDims function can be made more generic to get other ExtendedProperties.

    Regards
    Kez

Leave a Reply