pandas read excel sheet with multiple sheets and different header offsets - python

I have to read an Excel sheet in pandas which contains multiple sheets.
Unfortunately, the number of white space rows before the header starts seems to be different:
pd.read_excel('foo.xlsx', header=[2,3], sheet_name='first')
pd.read_excel('foo.xlsx', header=[1,2], sheet_name='second')
Is there an elegant way to fix this and read the Excel into a pandas.Dataframe with an additional column which contains the name of each sheet?
I.e. how can
pd.read_excel(file_name, sheet_name=None)
be passed a varying header argument or choose at least the 2 first (non empty) rows as header?
edit
dynamically skip top blank rows of excel in python pandas
seems to be related but not the solution as only the first headers are accepted.
edit2
Description of exact file structure:
... (varying number of empty rows)
__irrelevant_row__
HEADER_1
HEADER_2
where currently it is either 1 or 0 empty rows. But as pointed out in the comment it would be great if that would be more dynamic.

I am certain this could be done in a more neat fashion, but a way to achieve (I think) what you want is:
import openpyxl
import pandas as pd
book = openpyxl.load_workbook(PATH_TO_FILE)
for sh in book.sheetnames:
a = pd.DataFrame(book[sh].values).dropna(how='all').reset_index(drop=True)
a.columns = a.iloc[1]
a = a.iloc[2:]
a.iloc[0].index.name=sh
a["sheet"] = a.iloc[0].index.name
try:
b = b.append(a)
except NameError:
b = a.copy()
b.iloc[0].index.name = ''
print(b)
# header1 header2 sheet
#2 1 2 first
#3 3 4 first
#2 1 2 second
#3 3 4 second
#2 1 2 3rd
#3 3 4 3rd
Unfortunately I have no clue how it interacts with your actual data, but I do hope this helps you in your quest.

Related

How to create python function that performs multiple checks on a dataframe?

I have multiple inventory tables like so:
line no
-1 qty
-2 qty
1
-
3
2
42.1 FT
-
3
5
-
4
-
10 FT
5
2
1
6
6.7
-
or
line no
qty
1
2
2
4.5 KG
3
5
4
5
13
6
AR
I want to create logic check for the quantity column using python. (The table may have more than one qty column and I need to be able to check all of them. In both examples, I have the tables formatted as dataframes.)
Acceptable criteria:
integer with or without "EA" (meaning each)
"AR" (as required)
integer or float with unit of measure
if multiple QTY columns, then "-" is also accepted (first table)
I want to return a list per page, containing the line no. corresponding to rows where quantity value is missing (line 4, second table) or does not meet acceptance criteria (line 6, table 1). If the line passes the checks, then return True.
I have tried:
qty_col = [col for col in df.columns if 'qty' in col]
df['corr_qty'] = np.where(qty_col.isnull(), False, df['line_no'])
but this creates the quantity columns as a list and yields the following
AttributeError: 'list' object has no attribute 'isnull'
Intro and Suggestions:
Welcome to StackOverflow. Some general tips when asking questions on S.O. include as much information as possible. In addition, always identify the libraries you want to use and the accepted approach since there can be multiple solutions to the same problem, looks like you've done that.
Also, it is best to always share all, if not, most of your attempted solutions so others can understand the thought process and fully understand the best approach to provide a potential solution.
The Solution:
It wasn't clear if the solution you are looking for required that you read the PDF to create the dataframe or if converting the PDF to a CSV and processing the data using the CSV was sufficient. I took the latter approach.
import tabula as tb
import pandas as pd
#PDF file path
input_file_path = "/home/hackernumber7/Projects/python/resources/Pandas_Sample_Data.pdf"
#CSV file path
output_file_path = "/home/hackernumber7/Projects/python/resources/Pandas_Sample_Data.csv"
#Read the PDF
#id = tb.read_pdf(input_file_path, pages='all')
#Convert the PDF to CSV
cv = tb.convert_into(input_file_path, output_file_path, "csv", pages="all")
#Read initial data
id = pd.read_csv(output_file_path, delimiter=",")
#Print the initial data
print(id)
#Create the dataframe
df = pd.DataFrame(id, columns = ['qty'])
#Print the data as a DataFrame object; boolean values when conditions met
print(df.notna())

Replacing multiple dataframe headers with a single header with both header information

I have used pivot table in pandas and have got the desired format of dataframe but now I have two rows of header. The resultant dataframe after pivot table is as follows:
scenario Actual Plan
LY_USD_AMT USD_AMT LY_USD_AMT USD_AMT
package
Africa 3 3 0 0
Brazil 1 1 1 1
Canada 1 1 1 1
Mexico 0 0 1 1
I have managed to delete the last row of the header using the following:
pd_piv.columns = pd_piv.columns.droplevel(-1)
But at this point, it becomes difficult to identify which row is which as it renders column names like
LY_USD_AMT USD_AMT LY_USD_AMT USD_AMT
Is there anyway to resolve this issue, maybe combine the two headers and get a simpler tabular dataframe like the one below. I need a simple table since I am going to feed this to an external system which recognises only one header line.
ACTUAL_LY_USD_AMT ACTUAL_USD_AMT Plan_LY_USD_AMT Plan_USD_AMT
You can combine both the headers:
df.columns = [c[0] + "_" + c[1] for c in df.columns]
This would change the multiple headers to a combined header.
Eg.:
My dataframe with multiple headers:
location location2
S1 S2 S3 S1 S2 S3
a -1.268587 0.014928 0.121195 -1.250765 0.321319 0.017481
Output from the above code:
location_S1 location_S2 location_S3 location2_S1 location2_S2 location2_S3
a -1.268587 0.014928 0.121195 -1.250765 0.321319 0.017481
You can replace the columns with a list of whatever you want, and it will be converted to a proper index Pandas needs under the hood, so if the values that make up your column headings are strings, you can do something as simple as this:
pd_piv.columns = ['_'.join(header).upper() for header in pd_piv.columns]
So your columns end up being:
ACTUAL_LY_USD_AMT ACTUAL_USD_AMT PLAN_LY_USD_AMT PLAN_USD_AMT

Sorting Excel by 4 columns using Python (using win32com?)

I've been trying to sort my spreadsheet by 4 columns. Using win32com, I have managed to sort by 3 columns using the below code:
excel = win32com.client.Dispatch("Excel.Application")
wb= excel.Workbooks.Open('.xlsx')
ws= wb.worksheets[0]
ws.Range(D6:D110).Sort(Key1=ws.Range('D1'), Order1=1, Key2=ws.Range('E1'), Order2=2, Key3=ws.Range('G1'), Order3=3, Orientation=1)
However, when I try to add Key4, it says Key4 is an unexpected keyword argument. Is the Range.Sort function limited to only 3 keys? Is there a way to add a 4th?
Is there maybe another way to do this using pandas or openpyxl?
Thanks in advance!
Try reading in the excel sheet then sorting by header names. This assumes that your excel sheet is formatted correctly like a CSV.
import pandas as pd
df = pd.read_excel('filename.xlsx')
df = df.sort_values(['key1','key2','key3','key4'], axis=1)
df.to_excel('filename2.xlsx')
Simply sort twice or however many times needed in series of three keys.
xlAscending = 1
xlSortColumns = 1
xlYes = 1
ws.Range(D6:D110).Sort(Key1=ws.Range('D1'), Order1=xlAscending,
Key2=ws.Range('E1'), Order2=xlAscending,
Key3=ws.Range('G1'), Order3=xlAscending,
header=xlYes, Orientation=xlSortColumns)
# FOURTH SORT KEY (ADJUST TO NEEDED COLUMN)
ws.Range(D6:D110).Sort(Key1=ws.Range('H1'), Order1=xlAscending,
header=xlYes, Orientation=xlSortColumns)
By the way your Order numbers should only be 1, 2, or -4135 per the xlSortOrder constants.

Force Pandas to keep multiple columns with the same name

I'm building a program that collects data and adds it to an ongoing excel sheet weekly (read_excel() and concat() with the new data). The issue I'm having is that I need the columns to have the same name for presentation (it doesn't look great with x.1, x.2, ...).
I only need this on the final output. Is there any way to accomplish this? Would it be too time consuming to modify pandas?
you can create a list of custom headers that will be read into excel
newColNames = ['x','x','x'.....]
df.to_excel(path,header=newColNames)
You can add spaces to the end of the column name. It will appear the same in a Excel, but pandas can distinguish the difference.
import pandas as pd
df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]], columns=['x','x ','x '])
df
x x x
0 1 2 3
1 4 5 6
2 7 8 9

Reading values in column x from specific worksheets using pandas

I am new to python and have looked at a number of similar problems on SO, but cannot find anything quite like the problem that I have and am therefore putting it forward:
I have an .xlsx dataset with data spread across eight worksheets and I want to do the following:
sum the values in the 14th column in each worksheet (the format, layout and type of data (scores) is the same in column 14 across all worksheets)
create a new worksheet with all summed values from column 14 in each worksheet
sort the totaled scores from highest to lowest
plot the summed values in a bar chart to compare
I cannot even begin this process because I am struggling at the first point. I am using pandas and am having trouble reading the data from one specific worksheet - I only seem to be able to read the data from the first worksheet only (I print the outcome to see what my system is reading in).
My first attempt produces an `Empty DataFrame':
import pandas as pd
y7data = pd.read_excel('Documents\\y7_20161128.xlsx', sheetname='7X', header=0,index_col=0,parse_cols="Achievement Points",convert_float=True)
print y7data
I also tried this but it only exported the entire first worksheet's data as opposed to the whole document (I am trying to do this so that I can understand how to export all data). I chose to do this thinking that maybe if I exported the data to a .csv, then it might give me a clearer view of what went wrong, but I am nonethewiser:
import pandas as pd
import numpy as np
y7data = pd.read_excel('Documents\\y7_20161128.xlsx')
y7data.to_csv("results.csv")
I have tried a number of different things to try and specify which column within each worksheet, but cannot get this to work; it only seems to produce the results for the first worksheet.
How can I, firstly, read the data from column 14 in every worksheet, and then carry out the rest of the steps?
Any guidance would be much appreciated.
UPDATE (for those using Enthought Canopy and struggling with openpyxl):
I am using Enthought Canopy IDE and was constantly receiving an error message around openpyxl not being installed no matter what I tried. For those of you having the same problem, save yourself lots of time and read this post. In short, register for an Enthought Canopy account (it's free), then run this code via the Canopy Command Prompt:
enpkg openpyxl 1.8.5
I think you can use this sample file:
First read all columns in each sheet to list of columns called y7data:
y7data = [pd.read_excel('y7_20161128.xlsx', sheetname=i, parse_cols=[13]) for i in range(3)]
print (y7data)
[ a
0 1
1 5
2 9, a
0 4
1 2
2 8, a
0 5
1 8
2 5]
Then concat all columns together, I add keys which are used for axis x in graph, sum all columns, remove second level of MultiIndex (a, a, a in sample data) by reset_index and last sort_values:
print (pd.concat(y7data, axis=1, keys=['a','b','c']))
a b c
a a a
0 1 4 5
1 5 2 8
2 9 8 5
summed = pd.concat(y7data, axis=1, keys=['a','b','c'])
.sum()
.reset_index(drop=True, level=1)
.sort_values(ascending=False)
print (summed)
c 18
a 15
b 14
dtype: int64
Create new DataFrame df, set column names and write to_excel:
df = summed.reset_index()#.
df.columns = ['a','summed']
print (df)
a summed
0 c 18
1 a 15
2 b 14
If need add new sheet use this solution:
from openpyxl import load_workbook
book = load_workbook('y7_20161128.xlsx')
writer = pd.ExcelWriter('y7_20161128.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df.to_excel(writer, "Main", index=False)
writer.save()
Last Series.plot.bar:
import matplotlib.pyplot as plt
summed.plot.bar()
plt.show()
From what I understand, your immediate problem is managing to load the 14th column from each of your worksheets.
You could be using ExcelFile.parse instead of read_excel and loop over your sheets.
xls_file = pd.ExcelFile('Documents\\y7_20161128.xlsx')
worksheets = ['Sheet1', 'Sheet2', 'Sheet3']
series = [xls_file.parse(sheet, parse_cols=[13]) for sheet in worksheets]
df = pd.DataFrame(series)
And from that, sum() your columns and keep going.
Using ExcelFile and then ExcelFile.parse() has the advantage to load your Excel file only once, and iterate over each worksheet. Using read_excel makes your Excel file to be loaded in each iteration, which is useless.
Documentation for pandas.ExcelFile.parse.

Categories