How do I read a specific row in Excel using Python pandas?
I am trying to read a specific row from a spreadsheet and output it to a new spreadsheet.
The code I'm using is: import pandas as pd. From pandas import ExcelWriter. Excelfile = 'example.xlsx' writer = ExcelWriter(excelfile). Df = pd.readexcel(excelfile, 'Sheet1', index=False) writer.save() But this gives the error: Traceback (most recent call last): File "C:/Users/me/Desktop/python/test.py", line 7, in
File "C:UsersmeAppDataLocalProgramsPythonPython36libsite-packagespandasioexcel.py", line 1095, in init self.book = self.
How to get values of all rows in a particular column in openpyxl in Python?
Hi I have a scenario where I want to get values of all the rows in a particular column in an openpyxl sheet.
Let's say that my sheet has only 4 rows and it is called "Categories". In each row, there is a column with the name of product. So I want to get all the values of the name of product for all the rows. So I have this code:
With open("Categories", "rb") as f: wb = openpyxl.loadworkbook(f) sheet = wb.active for in range(4): for x in sheet.columns: if x.cell('product').value == 'apple':
print(x.cell('product').value)
However, this gives me error: AttributeError: 'Cell' object has no attribute 'row'. Does anyone know what I'm doing wrong? Thanks! The error you're getting is because x is a cell object, but you can't use any methods/attributes on x that you can't see. You need to convert x to a Range. For example:
For x in sheet.cell('product').value == 'apple':
productrow = sheet.row(x.row)
print(productrow.cell('product').value)
As @DanielW commented, you don't need to iterate over the rows to access the cells in the columns. You can directly loop through the rows of your dataframe like so: import pandas as pd. File = "products.xlsx" df = pd.readexcel(file, encoding = "ISO-8859-1") # Change to ISO-8859-1 or "UTF-8" for idx, row in df.iterrows(): for col in df.
Related Answers
How do I write to an existing Excel file in Python?
Let's take a step back. In this post, we'll write a simple Python script...
How do I create an Excel spreadsheet in Python?
I have a lot of data in Pandas and it can get quite bi...
How to fetch data from xlsx file in Python?
Python: reading from excel. Docs.readexcel PyExcel.ExcelObject I t...