<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by John A. Dungan on Medium]]></title>
        <description><![CDATA[Stories by John A. Dungan on Medium]]></description>
        <link>https://medium.com/@johnadungan?source=rss-a3f14654b6ab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wxYh0Vf17-GUpVGbwAGQHw.png</url>
            <title>Stories by John A. Dungan on Medium</title>
            <link>https://medium.com/@johnadungan?source=rss-a3f14654b6ab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:47:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@johnadungan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Better Chatbot: Replacing AWS Lex with ChatGPT]]></title>
            <link>https://medium.com/@johnadungan/building-a-better-chatbot-replacing-aws-lex-with-chatgpt-3319da7e5930?source=rss-a3f14654b6ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/3319da7e5930</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[John A. Dungan]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 20:29:42 GMT</pubDate>
            <atom:updated>2023-04-14T12:01:40.324Z</atom:updated>
            <content:encoded><![CDATA[<h3>Keep it simple and ChatGPT-4 will surprise you</h3><p>A couple years ago, I worked with a team of civic minded developers to combine Twilio and the AWS Lex service for a project called Courtbot. The end result worked, due to diligent efforts of one volunteer developer, but was difficult to maintain or add new features. Now that ChatGPT has entered the scene, I’m intrigued to see how it can handle the task.</p><p>In this article, I will share how I used ChatGPT to create a simple proof of concept prompt to gather information from users in a natural conversation.</p><p>I used the “gpt-4-0314” model for this experiment, but won’t be spending time on the details of the code. ChatGPT or Google will do a better job for you if that’s what you need. I am excited to share a couple surprises.</p><h4>What is my purpose?</h4><figure><img alt="A young robot cares about pancakes." src="https://cdn-images-1.medium.com/max/978/1*VU-kw9a61V35aFHTMXl33w.jpeg" /><figcaption>(credit: DALL-E)</figcaption></figure><p>With the new API format, introduced since “gpt-3.5-turbo”, you define the “system” role. This is the chance to set the tone of the chat, think of this as orientation for a new employee. It may be powerful, but you just have a simple task to perform:</p><blockquote>“You are a website service and your only goal is to ask users enough questions to get a case number. Until you get a case number your replies should always include a question about the information missing from the case number.”</blockquote><p>This sets the stage and should keep the conversation focused without too many distractions. After all, you don’t know what the user will ask.</p><h4>Now get more specific and add the rules:</h4><blockquote>“Ask questions to get the case number by asking for the court, type, year, and number in any order. Until you get a case number, your replies should always include a question about the information missing from the case number.”</blockquote><p>I added several details to provide information and hints for questions to ask the user. For example:</p><ul><li>Case numbers follow a specific format: “A case number is made of four parts separated by a hyphen. The parts are in this order court-type-year-number.”</li><li>Years are limited to a specific range: “Years are four digit integers between 1960 and 2023.”</li></ul><h4>First Surprise: this machine can read code</h4><p>I wasn’t looking forward to translating list of courts and case types into a prompt. Instead, I tried referring ChatGPT to a JSON object and it worked!</p><blockquote>“Courts and types are limited to a specific list: “Cases can only be from the json object called courts listed below. Types are a 1,2,or 3 chars symbol and can only be from the types json object listed below.”</blockquote><p>At the end of the prompt I copy and pasted objects that looked like this:</p><pre>courts = {{<br>&quot;adair&quot;: &quot;Adair&quot;,<br>&quot;alfalfa&quot;: &quot;Alfalfa&quot;,<br>…<br>}}</pre><p>and this:</p><pre>types = {{<br>AO&quot;: &quot;CIVIL ADMINISTRATIVE&quot;,<br>&quot;CF&quot;: &quot;CRIMINAL FELONY&quot;,<br>&quot;CJ&quot;: &quot;CIVIL RELIEF MORE THAN $10,000&quot;,<br>&quot;CM&quot;: &quot;CRIMINAL MISDEMEANOR&quot;,<br>&quot;FA&quot;: &quot;ADOPTION&quot;,<br>&quot;FD&quot;: &quot;FAMILY AND DOMESTIC&quot;,<br> …<br>}}</pre><p><strong><em>IMPORTANT</em></strong>: If you try this trick remember to escape your brackets like I did above. Maybe ChatGPT can figure out what you mean, but the Python library can’t.</p><h4>Keep it simple: this machine wants to talk, and talk, … and talk.</h4><p>The prompt is designed to supply lists of courts and types, but I add some important constraints to keep from losing the user’s interest:</p><blockquote>“You can provide lists of courts or types but never more than five at a time.”</blockquote><blockquote>You must be polite and only provide information and questions that help you discover the case number.”</blockquote><p>By limiting the number of options presented, the chatbot won’t get distracted. Here’s what happened when I tried:</p><pre>User: tell me a story<br>ChatGPT: I would love to, but my primary task is to help you find your case <br>number. First, can you provide the court where the case was filed?<br><br>User: write a poem about a case number<br>ChatGPT: I apologize, but I&#39;m here to help you find your case number. To <br>start, please let me know which court was the case filed in.</pre><h4>Surprise two: this machine knows things</h4><p>While I should have expected this, I was surprised that limiting responses did not limit its ability to draw on ChatGPT-4&#39;s general knowledge. For instance, without explicit prompting, the chatbot asked me for my location and suggest courts nearby. Locations of courts in relation to cities in Oklahoma is not in the prompt.</p><pre>ChatGPT: To find your case number, I&#39;ll need to ask you a few questions <br>related to your court case. What is the Court (the location) where your case<br>was filed? If unsure, could you let me know your location, so I can suggest <br>some nearby courts?<br>User: Edmond<br>ChatGPT: Thank you for providing your location. Here are some courts near <br>Edmond:<br><br>1. Oklahoma<br>2. Lincoln<br>3. Logan<br>4. Canadian<br>5. Payne<br><br>Which court is your case being handled in?</pre><p>It also can infer the the type of case based on general information. For example, if the user mentions the case is about a will the chatbot matches this to a probate case. I did not explain what types of matters are consider probate cases, but ChatGPT knows:</p><pre>ChatGPT: Thank you for providing the location. Can you please tell me the type<br>of your case? It can be civil, criminal, family, or appellate, among others.<br><br>User: the case is about a will<br><br>ChatGPT: Thank you for the information. In that case, the case type is <br>likely related to Probate. The most relevant type for a will is &quot;PB.&quot;</pre><h4>What I learned</h4><p>While it may be a while before I put ChatGPT into production, this proof-of-concept showed me some day I will. Compared to the AWS Lex system of intents and slots and integrating lambdas, I was able to make a better chatbot in about and hour of experimentation.</p><p>I you want to create your own chatbot keep these things in mind:</p><ul><li>Set boundaries to keep the chatbot on task</li><li>You can combine natural instructions and code</li><li>You can call on ChatGPT’s general knowledge</li></ul><p>I’ll be looking into that second suggestion for my next proof. I’d like to challenge ChatGPT to answer in code for immediate use. I’ll let you know what I find.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3319da7e5930" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Standing Up an API with GPT-4]]></title>
            <link>https://medium.com/@johnadungan/conquering-coding-challenges-with-gpt-4-crafting-a-compelling-fastapi-7b1dae4df208?source=rss-a3f14654b6ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b1dae4df208</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[gpt-4]]></category>
            <dc:creator><![CDATA[John A. Dungan]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 16:27:56 GMT</pubDate>
            <atom:updated>2023-03-20T17:49:51.883Z</atom:updated>
            <content:encoded><![CDATA[<p>Is ChatGPT an expensive search engine or a very cheap consultant?</p><p>I’m no stranger to challenges that accompany building web projects. From Google searches to parsing through the depths of Stack Overflow; the process can be time-consuming and frustrating.</p><p>Is GPT-4 an alternative? To find out, I bit the bullet, paid for ChatGPT Plus and started asking questions.</p><p><strong>The Challenge</strong></p><p>For some time, I’ve been exploring alternatives for extending the API services ofmy legal notification service <a href="https://docket2me.com/">docket2me.com</a>. I had a proof of concept built out of AWS pieces and parts but wanted something more manageable. With the advice of a friend, I settled on converting to a FastAPI server with a PostgreSQL database hosted on Heroku. I hesitated because I wanted all the things: managed migrations, a Swagger endpoint, handling CORS, JWT, and more. Some of these requirements I knew how to do from past projects, but some have always been handled by others on a team. I wanted to see how far I could get on my own with the help of my newly hired $20/month assistant.</p><p><strong>An AI That Knows Stuff</strong></p><p>From the get-go, ChatGPT provided straight forward answers to my questions, walking me through setting up the server, configuring the database, and managing migrations using Alembic and handle CORS in FastAPI. I used it to explain JWT authentication (pass, for now), and setting up FastAPI routers. I saved time and tedium when creating Pydantic models by just pasting in JSON examples of api payloads from my proof of concept project.</p><p>Not surprisingly, the more mature the technology the more confident you can be in the suggestions. For instance, Heroku has been around a while and GPT4&#39;s knowledge of the CLI is reliable.</p><p>I’m reluctant to anthropomorphize the AI, but our “conversation” was a helpful mix of code examples with instructions and reasoning for the suggestions being given. The kind of context you don’t get with web searching that gives you more confidence to use.</p><p><strong>Not Quite Perfect, but Still …</strong></p><p>Of course, my experience with ChatGPT wasn’t completely smooth. There were a few hiccups along the way, such as a Python error involving HMAC and byte strings when trying to meld the suggested auth method with my previous code. But even in these moments, ChatGPT was able to point out the point of failure and point to a solution.</p><p>And when it came to deploying my app to Heroku, there was an interesting issue I encountered with an incorrect PostgreSQL dialect in my DATABASE_URL. <strong>Know this:</strong> I don’t have patience for reading long stack traces, so when I ran into this I just pasted all of it and asked ChatGPT to explain. It quickly identified the problem, and here’s the interesting part, <strong><em>it didn’t know how to fix it</em>. </strong>But a quick google search using the explanation and I found <a href="https://help.heroku.com/ZKNTJQSK/why-is-sqlalchemy-1-4-x-not-connecting-to-heroku-postgres">the answer</a>. The point: I solved this in less than 10 minutes and know it would have taken more than an hour the old way.</p><p>A cycle emerged: try something, get an error, paste the error, get a suggestion to try. Of course, we all know this pattern, but<strong> </strong>ChatGPT helps you skip these steps: read 15 articles not quite related to the problem, watch 3 Youtube videos that might be related (or just funny), go get coffee, slack your friends wait for a reply.”</p><p><strong>A Surprisingly Positive Experience</strong></p><p>In the end, my experience with ChatGPT was far from perfect. There were problems that required my knowledge to resolve. This may be the most important point of the exercise: <strong><em>problems are inevitable, but ChatGPT helped me solve them faster and I never reached the point of having to walk away.</em></strong></p><p>The AI assistant enabled me to accomplish more in less time, without having to impose on friends for advice or spend hours trawling Google and Stack Overflow. I estimate I was able to accomplish in one focused day what would have taken 2–4 days, but that time would have been in competition with all the other priorities of my life.</p><p><strong><em>NOTE</em></strong><em>: I feel compelled to explain that 60% this article was created by by asking GPT-4 to summarize our chat as a medium article. I did spend some time adding background explanations to it and had to cut out the bits where ChatGPT shamelessly bragged about it’s abilities.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*Cpow_c62UcN2R6QOY8rWCg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b1dae4df208" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exporting Pandas Data to Elasticsearch]]></title>
            <link>https://medium.com/data-science/exporting-pandas-data-to-elasticsearch-724aa4dd8f62?source=rss-a3f14654b6ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/724aa4dd8f62</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[John A. Dungan]]></dc:creator>
            <pubDate>Sun, 24 Feb 2019 03:21:12 GMT</pubDate>
            <atom:updated>2021-06-12T14:46:14.610Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wJFOvN0DMd9GGhom" /><figcaption>Photo by <a href="https://unsplash.com/@chuttersnap?utm_source=medium&amp;utm_medium=referral">CHUTTERSNAP</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>How to send your dataframe rows to an elasticsearch database.</p><h3>Introduction</h3><p>So you’re done downloading and analyzing your data and ready to move it to an Elasticsearch database. This article covers preparing your data and sending it to an elasticsearch endpoint.</p><h4>Requirements</h4><pre>Python 3.6.5<br>numpy==1.15.0<br>pandas==0.23.4<br>elasticsearch==6.3.1</pre><pre>import numpy as np<br>import pandas as pd</pre><pre>from elasticsearch import Elasticsearch<br>from elasticsearch import helpers<br>es = Elasticsearch(http_compress=True)</pre><h3>Cleaning up your data</h3><p>Pandas dataframes are happy to hold NaN values in your data, but tolerance for null values is not a trait of elasticsearch. This makes sense when you think about it; you are asking an indexer to index nothing. You can avoid this by running your data through some simple functions.</p><h4>Blank Dates</h4><p>If your dataframe has blank dates, you’ll need to convert it to value elasticsearch accepts. Dates in elasticsearch can be formatted date strings (e.g. “6–9–2016&quot;), milliseconds since the Unix Epoch or seconds since the Unix Epoc (<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/date.html">elastic docs</a>). Null dates using the milliseconds since the Unix Epoch turns out to be January 1, 1970. If you have historical dates that include the early 70’s you may want to consider something else.</p><p>Here is a simple function you can use with dataframe .apply() to clean up your date columns.</p><pre>from datetime import datetime</pre><pre>def safe_date(date_value):<br>    return (<br>        pd.to_datetime(date_value) if not pd.isna(date_value)<br>            else  datetime(1970,1,1,0,0)<br>    )</pre><pre>df[&#39;ImportantDate&#39;] = df[&#39;ImportantDate&#39;].apply(safe_date)</pre><h4>Avoid Other Blank Values</h4><p>Any fields with blank values are just a problematic as empty dates. String values are easier than dates, but you need to supply a value. The code below swaps a blank for a safe string using the df.apply() function.</p><pre>def safe_value(field_val):<br>    return field_val if not pd.isna(field_val) else &quot;Other&quot;</pre><pre>df[&#39;Hold&#39;] = df[&#39;PossiblyBlankField&#39;].apply(safe_value)</pre><h4>Creating Documents</h4><p>Once you are confident your data is ready to send to Elasticsearch it’s time to convert a row into a document. Panda dataframes have a handy ‘iterrows’ function to make this straight forward. It returns an index of the row and an object containing the row values. This is a ‘pandas.core.series.Series’ object but behaves like a conventional python dict. This snippet demonstrates assigning the iter response to variables.</p><pre>df_iter = df.iterrows()</pre><pre>index, document = next(df_iter)</pre><p>Elasticsearch needs the data as a python dict which is easy enough using the .to_dict() method of the Series object. However, you can be selective about the data to be sent to the database and use a simple filter function. Notice that the function below returns a dict comprehension.</p><pre>use_these_keys = [&#39;id&#39;, &#39;FirstName&#39;, &#39;LastName&#39;, &#39;ImportantDate&#39;]</pre><pre>def filterKeys(document):<br>    return {key: document[key] for key in use_these_keys }</pre><h4>The Generator</h4><p>We are finally ready to send data to Elasticsearch using the python client and helpers. The helper.bulk api requires an instance of the Elasticsearch client and a generator. If you’re not familiar with generators go learn about their memory respecting benefits. If you don’t have time for that just understand the magic is the yield which a hands off data only as the bulk.helpers function asks for it. Here is the code for walking through your dataframe and shipping it off to Elasticsearch.</p><pre>from elasticsearch import Elasticsearch<br>from elasticsearch import helpers<br>es_client = Elasticsearch(http_compress=True)</pre><pre>def doc_generator(df):<br>    df_iter = df.iterrows()<br>    for index, document in df_iter:<br>        yield {<br>                &quot;_index&quot;: &#39;your_index&#39;,<br>                &quot;_type&quot;: &quot;_doc&quot;,<br>                &quot;_id&quot; : f&quot;{document[&#39;id&#39;]}&quot;,<br>                &quot;_source&quot;: filterKeys(document),<br>            }<br>    raise StopIteration</pre><pre>helpers.bulk(es_client, doc_generator(your_dataframe))</pre><h4>Breaking down the generated dict</h4><p>The doc_generator’s job is simply to provide a dict with certain values. Here are some comments on the details of what’s going on here.</p><pre>&quot;_index&quot;: &#39;your_index&#39;,</pre><p>This is the name of your index in Elasticsearch. If you don’t have an index, you can use any valid index name here. Elasticsearch will do it’s best to automatically index your documents. However, creating your index in advance is a good idea to avoid rejected documents and optimize the indexing process.</p><pre>&quot;_type&quot;: &quot;_doc&quot;,</pre><p>Take note: _type is being deprecated by Elasticsearch. Version 6.3.1 still supports named types, but this is a good time to start converting to ‘_doc’.</p><pre>“_id” : f”{document[‘id’]}”,</pre><p>The _id is a unique id for Elasticsearch. Don’t confuse it with your own ‘id’ field in your document. This might be a good place to add the index variable from itterows() to make the document more unique with something like f”{document[&#39;id&#39;]+index}&quot;.</p><pre>&quot;_source&quot;: filterKeys(document),</pre><p>The _source is the heart of this exercise: the document to be saved. Using document.to_dict() or any other valid python dict will work.</p><pre>raise StopIteration</pre><p>I include this line as a courtesy. The bulk.helpers function will handle an abrupt end of the generator. But raising the StopIteration saves it the trouble.</p><h3>Conclusion</h3><p>With attention to a few details transferring your pandas data to an Elasticsearch database can be drama free. Just remember that null values are a problem for elasticsearch. The rest is creating a generator to process your rows into python dictionaries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=724aa4dd8f62" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/exporting-pandas-data-to-elasticsearch-724aa4dd8f62">Exporting Pandas Data to Elasticsearch</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Expanding lists in panda dataframes]]></title>
            <link>https://medium.com/@johnadungan/expanding-lists-in-panda-dataframes-2724803498f8?source=rss-a3f14654b6ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/2724803498f8</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[dataframes]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lists]]></category>
            <dc:creator><![CDATA[John A. Dungan]]></dc:creator>
            <pubDate>Tue, 15 Jan 2019 17:45:37 GMT</pubDate>
            <atom:updated>2019-01-15T18:13:14.694Z</atom:updated>
            <content:encoded><![CDATA[<h3>Expanding lists in Pandas dataframes</h3><h4>How to expand a dataframe with a column of list values</h4><p>This is a common problem: you have a dataframe which includes a column with a list of values or objects. You need to flatten the data and turn it into a CSV or analyze the list, you’ll need to read each item and most likely want to preserve other fields on the row. You initially think this can be solved by a fancy, nested list comprehension. You’re close but pretty soon your head hurts trying to update your dataframe. Turning to stackoverflow, you find plenty of examples but none fit your needs.</p><p>This article presents a simple function developed for my notebooks after my own travel of the above cycle. Appropriate credit goes to <a href="https://stackoverflow.com/users/2180721/oleg">Oleg</a> on stackoverflow for the start of this solution in the question “<a href="https://stackoverflow.com/questions/32468402/how-to-explode-a-list-inside-a-dataframe-cell-into-separate-rows"><strong>How to explode a list inside a Dataframe cell into separate rows</strong></a>”. It should be noted that Oleg’s comment was not selected as the answer but it was a real help for me. I’ve turned his comment into a generic function which I can reuse</p><p>For those looking for the quick fix, here is the function ready for copying:</p><pre>import numpy as np<br>import pandas as pd</pre><pre>def expand_list(df, list_column, new_column): <br>    lens_of_lists = df[list_column].apply(len)<br>    origin_rows = range(df.shape[0])<br>    destination_rows = np.repeat(origin_rows, lens_of_lists)<br>    non_list_cols = (<br>      [idx for idx, col in enumerate(df.columns)<br>       if col != list_column]<br>    )<br>    expanded_df = df.iloc[destination_rows, non_list_cols].copy()<br>    expanded_df[new_column] = (<br>      [item for items in df[list_column] for item in items]<br>      )<br>    expanded_df.reset_index(inplace=True, drop=True)<br>    return expanded_df</pre><pre><br>#usage</pre><pre>expanded_dataframe = expand_list(old_dataframe,&quot;Item List&quot;, &quot;Item&quot;)</pre><p>The rest of this article will be explaining how it works. I found it helpful to walk through each line of the function. This helps in understanding how to achieve the current goal but also provides some useful techniques for other dataframe challenges.</p><h4><strong>Requirements</strong></h4><p>Here are the details of my environment</p><pre>Python 3.6.5<br>numpy==1.15.0<br>pandas==0.23.4</pre><h4><strong>The Arguments</strong></h4><ul><li><strong>df</strong>: This is the pandas dataframe containing a column with a list.</li><li><strong>list_column</strong>: a string with the name of the column in question</li><li><strong>new_column</strong>: a string naming a new column where you want the results to be saved. This can be the same as the column with the lists, but you will lose the original values.</li></ul><h4><strong>Size Up the Data</strong></h4><p>First step, we create a pandas Series object with the length of each list in the column. Normally, you supply a custom function to the .apply() method of the dataframe but in this case the python’s built-in ‘len’ function works just fine.</p><pre>lens_of_lists = df[list_column].apply(len)</pre><p>Next, we create a range from the number of rows in the dataframe.</p><pre>origin_rows = range(df.shape[0])</pre><p>Then create a numpy array with an item for each value in all of the lists. This is a map for creating a new column. Each item in ‘destination_rows’ has the index to the original row which will be the source of the new data.</p><pre>destination_rows = np.repeat(origin_rows, lens_of_lists)</pre><h4><strong>Create a New Dataframe</strong></h4><p>Now we are ready to create a new dataframe. Step one, get the index of all the other columns in the dataframe.</p><pre>non_list_cols = [idx for idx, col in enumerate(df.columns) <br>                 if col != list_column]</pre><p>Create a new dataframe by copying the data using the row and column information. If you examine the dataframe at this point it is pretty useless; it contains lots of duplicated rows.</p><pre>expanded_df = df.iloc[destination_rows, non_list_cols].copy()</pre><p>To make the new dataframe useful we need to get all the items in each of the lists. Now is the time for a nested list comprehension to expand the list values into a flat array. You could have done this at the start, but you had to do all the other bits for it to have proper home where the data fits and the original values are preserved.</p><pre>expanded_df[new_column] = [i for items in df[list_column]<br>                             for i in items]</pre><p>One last bit of housecleaning to reset the dataframe index and you’re ready to return a new dataframe.</p><pre>expanded_df.reset_index(inplace=True, drop=True)</pre><pre>return expanded_df</pre><h4>Conclusion</h4><p>This function was written for cleaning data in a jupyter notebook and performs well for my circumstance. You may need to tweak it for your situation. Keep in mind it can only expand one field at a time. If you have two columns with list information, you have to run the function twice. You’ll also have to figure out how to manage all the duplicate data. Similarly, you’ll have to run over the dataframe twice if your list also contains a list. No doubt this could be handled with some recursive fun but for the moment this should suffice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*Gy6EdNKPXr7ruiycd2JyxA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2724803498f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using painless in Kibana to calculate days between dates]]></title>
            <link>https://medium.com/@johnadungan/using-painless-in-kibana-to-calculate-days-between-dates-40855cc34b16?source=rss-a3f14654b6ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/40855cc34b16</guid>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[painless]]></category>
            <category><![CDATA[kibana]]></category>
            <dc:creator><![CDATA[John A. Dungan]]></dc:creator>
            <pubDate>Sat, 29 Dec 2018 22:32:08 GMT</pubDate>
            <atom:updated>2019-01-09T18:00:47.801Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Painless in Kibana to calculate days between dates</h3><p>As a new Kibana user I am enjoying it as a way to get into Elasticsearch and especially happy with how easy it is to build dashboards and visualizations. I was surprised to find that writing scripted fields for date values is not so easy. For anyone else discovering Kibana and the painless language I’m offering this solution to the simple question: how many days apart are two dates?</p><h3>Introduction</h3><p>I’m going to layout the particulars of how my date fields came to be in elasticsearch so you can recreate it or match it against your situation. If you, like me sometimes, are in the midst of frantic search for an immediate solution, <em>skip to the bottom for the </em><a href="https://medium.com/p/40855cc34b16#80bd"><em>painless code</em></a><em>.</em></p><p>The goal of this article is to show you how to create a scripted field in Kibana to show the number of days between a two events. This field will be an integer. In the cases where the second event has not happened, I’d like to know how many days have passed since the first event happened.</p><p>The code snippets are meta examples to give you and idea of the concept without getting you bogged down on the details of my project. As such, they are abbreviated and may not be the full solution. Keep this in mind if you are copying and pasting into your project.</p><p>To set the stage, here are the main components of my project:</p><ul><li>Python 3.6.5</li><li>numpy==1.15.0</li><li>pandas==0.23.4</li><li>elasticsearch-6.5.0</li><li>kibana-6.5.0-darwin-x86_64</li></ul><h4>The Data Pipeline</h4><p>The data for my project comes from a CSV file. The date fields in question start out as strings formatted as ‘10/24/2018’ for example. I use pandas to retrieve the data and perform a conversion to python datetime. Then each row of the dataframe is stored in elastic search as document. Bulk transfer is a bit complicated and best left to another article.</p><p>An important detail. Elastic search can’t index something that doesn’t exist. Trying to store a document with a null field value is a bit like dividing by zero. The elasticsearch API will yell at you and your database will be missing these records. This occurs in my date because I have a date field for something that may or may not have happened.</p><p>The fix is to change the null values to the Unix Epoch value (or zero milliseconds from the start of 1970). Yes, this is an arbitrary value and causes problems if you have historical dates. This project doesn’t so I’m comfortable with the choice.</p><p>The date fields for this example are the columns ‘FirstDate’ and ‘SecondDate’ FirstDate is the event that created the record, so it will always have a value. SecondDate is the date that may or may not have happened and needs to be checked for safety.</p><p>Pandas does the work with pd.isna() checking for missing data and pd.to_datetime() doing the conversion. The unix epoch is supplied by datetime(1970,1,1,0,0).</p><pre>from datetime import datetime<br>import numpy as np<br>import pandas as pd</pre><pre>raw_data = pd.read_csv(&#39;raw_data.csv&#39;)</pre><pre>def pd_to_datetime(date_value):<br>   return <strong>pd.to_datetime(date_value)</strong> if not <strong>pd.isna(date_value) </strong>else <strong>datetime(1970,1,1,0,0)</strong></pre><pre>raw_data[‘FirstDate’]= raw_data[‘FirstDate’].apply(pd_to_datetime)</pre><pre>raw_data[‘SecondDate’]= raw_data[‘SecondDate’].apply(pd_to_datetime)</pre><pre># use elasticsearch.py to send docs to elastic search...</pre><h4>Index Details</h4><p>The fields of the index where the documents are stored use the out-of-the-box date type. Just in case you need them, here is a snippet for your index:</p><pre> “mappings”: {<br>     “_doc”: {<br>         “properties”: {<br>              “FirstDate”: {“type”: “date”},<br>              “SecondDate”: {“type”: “date”},<br>          }<br>       }<br>   }</pre><h4>Scripted Fields</h4><p>Finally, we get to Kibana! Scripted fields are part of an index pattern. Look for the ‘Scripted Fields’ Tab and find this button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*jmEfZiNWUzg8Ra5uj19Org.png" /></figure><p>These are the setting I use for the new field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTlDFgEBle3bhQFc6nCReQ.png" /></figure><h4>Painless Code</h4><p>Here is the painless code to calculate the number of days between two dates. Remember the Unix Epoch value? It gets converted by getMillis() to zero. This code looks for the zero and returns the days since the first event.</p><pre>def FirstDate =  doc[&#39;FirstDate&#39;].date.getMillis();<br>def SecondDate = doc[&#39;SecondDate&#39;].date.getMillis();<br>def now = new Date().getTime();</pre><pre>if (SecondDate == 0){<br>    return (now - FirstDate) / (1000*60*60*24)<br>}<br>return (SecondDate-FirstDate) / (1000*60*60*24)</pre><p>There are improvements to be made to this solution. It would be nice to have a date value results in case I want to know how many days and hours between events. Saving the Date() and calculating milliseconds in a day aren’t efficient either, but my project only deals with thousands of records so performance is not a priority.</p><h4>Conclusion</h4><p>I took a good portion of a day working out this dependable solution. The documents on painless are there but difficult to navigate. There are a handful of stackoverflow questions close to this problem, but none that fit my needs. All assume a good knowledge of the standard Java libraries. As a python guy, this simple approached works for my project and I can move on to the next problem. I hope this helps you too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*37OuOufQhPqFRNSGwGEYbA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40855cc34b16" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>