Pandas: Call other function when crawling a DataFrame with a function
<p>Using <code>Pandas</code>, I have this function which reads every row in a DataFrame and assigns the column value to a corresponding variable. Each pass in the function handles a row in the DataFrame and thus overwrites the variables.</p>

<p>I'm planning on adding more columns/variables and I find the coding to be quite inelegant because of the redundancy.</p>

<pre><code>import pandas as pd

df = pd.DataFrame([["Big red shirt", "Red", "L", "Shirt", "2016"], ["Medium black jeans", "Black", "M", "Pants", "2016"], ["Small blue shirt", "Blue", "S", "Shirt", "2016"]], columns=['Name', 'Color', 'Size', 'Category', 'Year'])

def crawl(assign):
    try:
        name = assign["Name"]
    except:
        name = None
    try:
        color = assign["Color"]
    except:
        color = None
    try:
        size = assign["Size"]
    except:
        size = None
    try:
        category = assign["Category"]
    except:
        category = None
    try:
        year = assign["Year"]
    except:
        year = None

df2[(["Name", "Color", "Size", "Category", "Year"])].apply(crawl, axis=1)
</code></pre>

<hr>

<h2>Desired result</h2>

<ul>
<li><p>I would instead like to use a briefer <code>function</code> which, according to the same principle above, takes each cell in the DataFrame from the columns and assigns it to corresponding variable (<code>name</code>, <code>color</code>, etc). </p></li>
<li><p>If the corresponding cell in the DataFrame is empty, then the variable is set to <code>None</code>.</p></li>
</ul>

<h2>My attempt</h2>

<p>I started working on a solution which uses the below function – which is not tested! However, I'm unsure how to implement it in the main scheme of things since the function would have to call on <code>assign</code> in the original function <code>crawl</code>.</p>

<pre><code>def get_cell(variables, *column_names):
    for var in variables:
        for col in list(column_names):
            try:
                var = assign[col]
            except:
                var = None
            finally:
                return var

get_cell(([name, color, size, category, year]), ["Name"], ["Color"], ["Size"], ["Category"], ["Year"])
</code></pre>

<hr>

<h2>Sample data</h2>

<pre><code>df = pd.DataFrame([["Big red shirt", "Red", "L", "Shirt", "2016"], ["Medium black jeans", "Black", "M", "Pants", "2016"], ["Small blue shirt", "Blue", "S", "Shirt", "2016"]], columns=['Name', 'Color', 'Size', 'Category', 'Year'])
</code></pre>

<p>The DataFrame looks like this:</p>

<pre><code>Name                    Color     Size     Category     Year
"Big red shirt"         "Red"     "L"      "Shirt"      "2016"
"Medium black jeans"    "Black"   "M"      "Pants"      "2016"
"Small blue shirt"      "Blue"    "S"      "Shirt"      "2016"
</code></pre>