Note that there are some explanatory texts on larger screens.

plurals
  1. POComplicated (for me) reshaping from wide to long in Pandas
    primarykey
    data
    text
    <p>Individuals (indexed from 0 to 5) choose between two locations: A and B. My data has a wide format containing characteristics that vary by individual (ind_var) and characteristics that vary only by location (location_var).</p> <p>For example, I have:</p> <pre><code>In [281]: df_reshape_test = pd.DataFrame( {'location' : ['A', 'A', 'A', 'B', 'B', 'B'], 'dist_to_A' : [0, 0, 0, 50, 50, 50], 'dist_to_B' : [50, 50, 50, 0, 0, 0], 'location_var': [10, 10, 10, 14, 14, 14], 'ind_var': [3, 8, 10, 1, 3, 4]}) df_reshape_test Out[281]: dist_to_A dist_to_B ind_var location location_var 0 0 50 3 A 10 1 0 50 8 A 10 2 0 50 10 A 10 3 50 0 1 B 14 4 50 0 3 B 14 5 50 0 4 B 14 </code></pre> <p>The variable 'location' is the one chosen by the individual. dist_to_A is the distance to location A from the location chosen by the individual (same thing with dist_to_B)</p> <p>I'd like my data to have this form:</p> <pre><code> choice dist_S ind_var location location_var 0 1 0 3 A 10 0 0 50 3 B 14 1 1 0 8 A 10 1 0 50 8 B 14 2 1 0 10 A 10 2 0 50 10 B 14 3 0 50 1 A 10 3 1 0 1 B 14 4 0 50 3 A 10 4 1 0 3 B 14 5 0 50 4 A 10 5 1 0 4 B 14 </code></pre> <p>where choice == 1 indicates individual has chosen that location and dist_S is the distance from the location chosen.</p> <p>I read about the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="noreferrer" title=".stack">.stack</a> method but couldn't figure out how to apply it for this case. Thanks for your time!</p> <p>NOTE: this is just a simple example. The datasets I'm looking have varying numbers of location and number of individuals per location, so I'm looking for a flexible solution if possible</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload