Create Pyspark Dataframe from Key Value Pair log file with variable contents - python-3.x

I have a log file in key=value pair format and would like to read the contents into an rdd, process the rdd into a data frame, and perform aggregations/analysis with spark SQL. I can read the raw data to rdd but I haven't been able to find an example of how to process key value pairs into a tabular format.
To complicate matters, the log can and does have missing key value pairs, so the format is variable. I would hope to be able to get around this by having NULL values in rows where that 'column'/key=value is missing once processed to data frame.
Below is an example of the log :
"Date"="2017-07-11T15:55:07-07:00","recordType"="ap_data","apName"="ap1","numClients"="5","version"="2.1"
"Date"="2017-07-11T15:55:07-07:00","recordType"="ap_data","apName"="ap2","numClients"="4","version"="2.1"
"Date"="2017-07-11T15:55:07-07:00","recordType"="ap_data","apName"="ap3","version"="2.1"
Notice the third event is missing the "numClients" key-value pair.
All I've managed to do so far is read the raw content to RDD:
#Initializing PySpark
from pyspark import SparkContext, SparkConf
from pyspark.context import SparkContext
from pyspark.sql.types import Row
sc = SparkContext.getOrCreate()
# Read raw contents to a new RDD and print first 2 results
raw_data = sc.textFile("log_sample.log")
raw_data.take(2)
Kindly please provide some help with reading key-value pair formatted data and processing to tabular format. Else, if this is not the right approach, I'm open to suggestion(s). Thank you!
Below is the data frame structure I hope to produce:
EDIT: Apologies, for clarity I'm not trying to produce any HTML, just wanted to show an example of tabular result, not sure why the html is showing and not just rendering the table.
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg .tg-yw4l{vertical-align:top}
</style>
<table class="tg">
<tr>
<th class="tg-yw4l">Date</th>
<th class="tg-yw4l">recordType</th>
<th class="tg-yw4l">apName</th>
<th class="tg-yw4l">numClients</th>
<th class="tg-yw4l">version</th>
</tr>
<tr>
<td class="tg-yw4l">2017-07-11T15:55:07-07:00</td>
<td class="tg-yw4l">ap_data</td>
<td class="tg-yw4l">ap1</td>
<td class="tg-yw4l">5</td>
<td class="tg-yw4l">2.1</td>
</tr>
<tr>
<td class="tg-yw4l">2017-07-11T15:55:07-07:00</td>
<td class="tg-yw4l">ap_data</td>
<td class="tg-yw4l">ap2</td>
<td class="tg-yw4l">4</td>
<td class="tg-yw4l">2.1</td>
</tr>
<tr>
<td class="tg-yw4l">2017-07-11T15:55:07-07:00</td>
<td class="tg-yw4l">ap_data</td>
<td class="tg-yw4l">ap3</td>
<td class="tg-yw4l"></td>
<td class="tg-yw4l">2.1</td>
</tr>
</table>

Related

Colspan not working properly using Python Pandas

I have some data that i need to convert into an Excel sheet which needs to look like this at the end of the day:
I've tried the following code:
import pandas as pd
result = pd.read_html(
"""<table>
<tr>
<th colspan="2">Status N</th>
</tr>
<tr>
<td style="font-weight: bold;">Merchant</td>
<td>Count</td>
</tr>
<tr>
<td>John Doe</td>
<td>10</td>
</tr>
</table>"""
)
writer = pd.ExcelWriter('out/test_pd.xlsx', engine='xlsxwriter')
print(result[0])
result[0].to_excel(writer, sheet_name='Sheet1', index=False)
writer.save()
This issue here is that the colspan is not working properly. The output is like this instead:
Can someone help me on how i can use colspan on Python Pandas?
It would be better if i don't have to use read_html() and do it directly on python code but if it's not possible, i can use read_html()
Since Pandas can't recognize the values and columns title you should introduce them, if you convert HTML text to the standard format, then pandas can handle it correctly. use thead and tbody to split header and values like this.
result = pd.read_html("""
<table>
<thead>
<tr>
<th colspan="2">Status N</th>
</tr>
<tr>
<td style="font-weight: bold;">Merchant</td>
<td>Count</td>
</tr>
</thead>
<tbody>
<tr>
<td>John Doe</td>
<td>10</td>
</tr>
</tbody>
</table>
"""
)
To write Dataframe to an excel file you can use the pandas to_excel method.
result[0].to_excel("out.xlsx")

Stemming a list of words in a dataframe

<html>
<body>
<table border=1>
<tr>
<th>label</th>
<th>rev</th>
</tr>
<tr>
<td>0</td>
<td>[ story man unnatural feelings pig...] </td>
</tr>
<tr>
<td>0</td>
<td>[ airport starts brand new luxury ...] </td></tr>
<tr>
<td>0</td>
<td>[ film lacked something couldnt pu...] </td></tr>
<tr>
<td>0</td>
<td>[ sorry everyone know supposed art...] </td></tr>
<tr>
<td>0</td>
<td>[ little parents took along theate..]</td></tr>
</table>
</body>
</html>
IMAGE-> [1]: https://i.stack.imgur.com/j2EAK.jpg
My dataframe looks like above, I tried the below code to stem it :
from nltk.stem.porter import PorterStemmer
ps=PorterStemmer()
da.rev=[ps.stem(word) for word in da.loc[:,'rev']]
but it was resulting in the same data frame again, can't point out what went wrong.
Any help will be dearly appreciated. Thank you for your time
Hard to say without seeing your exact code but if each item in the series is a list of strings you could try
da.rev.apply(lambda x: [ps.stem(word) for word in x])

select specific rows with class names

I am parsing an HTML which has bunch of rows that I want to select. Here are example of those rows
<tr class="constantstring-randomvalue1-row" onmouseover="this.className='constantstring-light-row-cp-h'" onmouseout="this.className='constantstring-randomvalue1-row'" onclick="if(ignoreOnClick==false)window.location='find.ashx?cv3dsw'" valign="top">
<tr class="constantstring-randomvalue1-row" onmouseover="this.className='constantstring-light-row-cp-h'" onmouseout="this.className='constantstring-randomvalue1-row'" onclick="if(ignoreOnClick==false)window.location='find.ashx?cv3dsw'" valign="top">
<tr class="constantstring-randomvalue2-row-2" onmouseover="this.className='constantstring-light-row-cp-h'" onmouseout="this.className='constantstring-randomvalue2-row-2'" onclick="if(ignoreOnClick==false)window.location='find.ashx?cv3dsw'" valign="top">
<tr class="constantstring-randomvalue2-row-2" onmouseover="this.className='constantstring-light-row-cp-h'" onmouseout="this.className='constantstring-randomvalue2-row-2'" onclick="if(ignoreOnClick==false)window.location='find.ashx?cv3dsw'" valign="top">
What i was trying to do is use BeautifulSoup4 and find_all using a regex find_all(re.compile(regext))
However, the problem is that i am unable to come up with a good regext which will select all rows that i am interested in.
all the rows that i want start with constantstring-. I don't care what it is followed by. What would be the proper way, should i use re.compile and if so, what will be the correct regex?
If you want to accomplish this with RE the following will do, I added an extra row to demo it not picking up the final row.
http://rextester.com/OSSFB8621
from bs4 import BeautifulSoup
import re
html ="""
<tr class="constantstring-randomvalue1-row" onmouseover="this.className='constantstring-light-row-cp-h'" onmouseout="this.className='constantstring-randomvalue1-row'" onclick="if(ignoreOnClick==false)window.location='find.ashx?cv3dsw'" valign="top">
<tr class="constantstring-randomvalue1-row" onmouseover="this.className='constantstring-light-row-cp-h'" onmouseout="this.className='constantstring-randomvalue1-row'" onclick="if(ignoreOnClick==false)window.location='find.ashx?cv3dsw'" valign="top">
<tr class="constantstring-randomvalue2-row-2" onmouseover="this.className='constantstring-light-row-cp-h'" onmouseout="this.className='constantstring-randomvalue2-row-2'" onclick="if(ignoreOnClick==false)window.location='find.ashx?cv3dsw'" valign="top">
<tr class="constantstring-randomvalue2-row-2" onmouseover="this.className='constantstring-light-row-cp-h'" onmouseout="this.className='constantstring-randomvalue2-row-2'" onclick="if(ignoreOnClick==false)window.location='find.ashx?cv3dsw'" valign="top">
<tr class="axcconstantstring-randomvalue2-row-2" onmouseover="this.className='constantstring-light-row-cp-h'" onmouseout="this.className='constantstring-randomvalue2-row-2'" onclick="if(ignoreOnClick==false)window.location='find.ashx?cv3dsw'" valign="top">
"""
bs = BeautifulSoup(html,'lxml')
for tr in bs.find_all("tr", {"class" : re.compile('^(constantstring)')}):
print(tr)
Instead of regex you can use in-built string methods for the same task. Like,
rows = soup.find_all('tr)'
selected_rows = [i for i in rows if str(i).startswith('tr class="constantstring-randomvalue')]
If you miss str() the if condition will fail.
Hope this helps! Cheers!

Formatting HTML Tables for Excel

I have a page in asp that makes a xls table, however when open the table all the rows are stuffed into the default column width which I would like to set.
My table looks something like this:
<table>
<thead>
'A for loop makes a series of th
</thead>
'another loop pulls db values
<tr><td>value1</td><td>value2</td> 'etc </tr>
</table>
I have tried the following to set the space
width="3.29in"
&nsp; spam (barbaric but sometimes effective)
width="400px"
style="width:300px"
none of the above seem to work.
Additionally here is my header asp incase its relevant
Response.Clear()
Response.Buffer = False
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "Content-Disposition", "attachment; filename=blah.xls"
Also on a side note for some reason when I have a dollar value printed as such
<td>$<%=dbvalue%></td>
for some reason this yields '$dollar value and I am not sure how to nuke the single quote.
Do you need the thead tag? Something like this should work:
<html>
<body>
<h1>Report Title</h1>
<table >
<tr>
<th style="width : 300px">header1</th>
<th style="width : 100px">header2</th>
<th style="width : 200px">header..</th>
<th style="width : 300px">....</th>
</tr>
<tr class="row1">
<td >value1</td>
<td >value2</td>
<td >value..</td>
<td >....</td>
</tr>
....
Optionally you can put the table row with th tags inside a <thead> tag

Watir: How to access a table without an ID or NAME

I am trying to write my watir script to grab the following data (the table body headers and the table row data, but I am having trouble trying to figure out how to access the table. (Once I get that, teh rest is a piece of cake).
Can anyone come up with something that will help me access the table? It doesn't have a name or an ID...
<div id="income">
<table class="tHe" cellspacing="0">
<thead>
<tr>
<th id="companyLabel" class="tFirst" style="width:30%"> Quarter Ending </th>
<th id="201004" class="tFirst right">Apr 10 </th>
<th id="201001" class="tFirst right">Jan 10 </th>
<th id="200910" class="tFirst right">Oct 09 </th>
<th id="200907" class="tFirst right">Jul 09 </th>
<th id="200904" class="tFirst right">Apr 09 </th>
</tr>
</thead>
<tbody id="revenueBody">
<tr>
<td class="indtr">Totals</dfn></td>
<td class="right">2849.00</td>
<td class="right">3177.00</td>
<td class="right">5950.00</td>
<td class="right">4451.00</td>
<td class="right">3351.00</td>
</tr>
...
ie.table(:class=>'tHe') should work if there's no other tables with the same class name
ie.table(:after?, ie.div(:id, 'income')) should work if there's no other div with id 'income'
or ie.table(:index=>0) - you would need to check your page to see what the correct index value for your table is.
But wait, there is more! :)
browser.div(:id => "income").table(:class => 'tHe')
browser.div(:id => "income").table(:index => 1)
...
There is also XPath if you are stuck.
If you fire up the page and access it through Firebug or your browser's native developer tools, you can find the xpath expression for the table and then plug that into the Watir API call.
I think it was in later versions of Watir 1.5.x that support for advanced page querying came in (basically your problem, where there are no ID tags). This page on the watir wiki should help:
Ways Available To Identify HTML Element

Resources