Derive extra column from Pandas dataframe columns
<p>Given a dataframe, how to add an extra column which is derived from the columns in the dataframe i.e.</p>

<pre><code>data = {'date': ['2016-01-01', '2016-01-01', '2016-01-02'],
        'number': [10, 21, 20],
        'location': ['CA', 'NY', 'NJ']
        }

print pd.DataFrame(data)

  location  number        date
0       CA      10  2016-01-01
1       NY      21  2016-01-01
2       NJ      20  2016-01-02
</code></pre>

<p>I want to generate an extra column from <code>location</code> and <code>date</code> i.e.get date and then generate key values for <code>extra_column</code> where key is <code>date + i</code> and value is some random string. Where <code>i = random.randint(1,3)</code></p>

<pre><code>  location  number       date     extra_column
0       CA      10  2016-01-01    {{2016-01-01, CA}, {2016-01-02, something}, {2016-01-03, something else}}
1       NY      21  2016-01-01    {{2016-01-01, NY}, {2016-01-02, someplace}}
2       NJ      20  2016-01-02    {{2016-01-02, NJ}, {2016-01-03, anything}}
</code></pre>

<p>You can write a function do to the manipulation with the current columns and just add the column to the <code>DataFrame</code>. See the code below:</p>

<pre><code>import pandas as pd

data = {'date': ['2016-01-01', '2016-01-01', '2016-01-02'],
        'number': [10, 21, 20],
        'location': ['CA', 'NY', 'NJ']
        }

df = pd.DataFrame(data)

def somefunc(date, location):
    # some code to generate extra column


date_vals = df['date'].values
loc_vals = df['location'].values

new_col_vals = somefunc(date_vals, loc_vals)

# add the column by doing the following
df['new_col'] = new_col_vals
</code></pre>

<p>Hope it helps.</p>

python pandas