Explode a row to multiple rows in pandas dataframe
<p>I have a dataframe with the following header: </p>

<pre><code>id, type1, ..., type10, location1, ..., location10
</code></pre>

<p>and I want to convert it as follows: </p>

<pre><code>id, type, location 
</code></pre>

<p>I managed to do this using embedded for loops but it's very slow: </p>

<pre><code>new_format_columns = ['ID', 'type', 'location'] 
new_format_dataframe = pd.DataFrame(columns=new_format_columns)



print(data.head())
new_index = 0 
for index, row in data.iterrows(): 
        ID = row["ID"]

        for i in range(1,11):
                if row["type"+str(i)] == np.nan:
                        continue
                else:
                        new_row = pd.Series([ID, row["type"+str(i)], row["location"+str(i)]])
                        new_format_dataframe.loc[new_index] = new_row.values
                        new_index += 1
</code></pre>

<p>Any suggestions for improvement using native pandas features? </p>

<p>You can use <code>lreshape</code>:</p>

<pre><code>types = [col for col in df.columns if col.startswith('type')]
location = [col for col in df.columns if col.startswith('location')]

print(pd.lreshape(df, {'Type':types, 'Location':location}, dropna=False))
</code></pre>

<p>Sample:</p>

<pre><code>import pandas as pd

df = pd.DataFrame({
'type1': {0: 1, 1: 4}, 
'id': {0: 'a', 1: 'a'}, 
'type10': {0: 1, 1: 8},
'location1': {0: 2, 1: 9},
'location10': {0: 5, 1: 7}})

print (df)
  id  location1  location10  type1  type10
0  a          2           5      1       1
1  a          9           7      4       8

types = [col for col in df.columns if col.startswith('type')]
location = [col for col in df.columns if col.startswith('location')]

print(pd.lreshape(df, {'Type':types, 'Location':location}, dropna=False))
  id  Location  Type
0  a         2     1
1  a         9     4
2  a         5     1
3  a         7     8
</code></pre>

<hr>

<p>Another solution with double <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a>:</p>

<pre><code>print (pd.concat([pd.melt(df, id_vars='id', value_vars=types, value_name='type'),
                  pd.melt(df, value_vars=location, value_name='Location')], axis=1)
         .drop('variable', axis=1))

  id  type  Location
0  a     1         2
1  a     4         9
2  a     1         5
3  a     8         7
</code></pre>

python pandas explode reshape melt