Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH/BUG: support multi-index slicing assignment expansions #7475

Closed
jreback opened this issue Jun 16, 2014 · 1 comment
Closed

ENH/BUG: support multi-index slicing assignment expansions #7475

jreback opened this issue Jun 16, 2014 · 1 comment

Comments

@jreback
Copy link
Contributor

jreback commented Jun 16, 2014

From SO:
http://stackoverflow.com/questions/24247255/idiomatic-multiindex-column-assignment-in-pandas/24247513#24247513
http://stackoverflow.com/questions/24258781/advanced-cross-section-with-multi-index-in-pandas

ix = pd.MultiIndex.from_tuples(list(enumerate(np.random.choice(['A', 'B'], 5))))
df = pd.DataFrame({'Val': np.random.randint(0, 30, 5)}, index=ix).unstack().fillna(0)
df
   Val    
     A   B
0   27   0
1    0   3
2    0   7
3    9   0
4    0  19

I think this could be make to work (its column creation)

df['Half'] = df['Val']/2

concat soln
Automatic broadcasting (but need to not 'align')

    In [59]: concat([df['Val'],df['Val']/2],axis=1,keys=['Val','Half'])
    Out[59]: 
       Val      Half              
         A   B     A    B
    0    0  10   0.0  5.0
    1    0  10   0.0  5.0
    2    0  13   0.0  6.5
    3   27   0  13.5  0.0
    4    2   0   1.0  0.0
In [42]: In 
[107]: df = pd.DataFrame(np.arange(5*12).reshape(-1,12), columns=col)

In [108]: df
Out[108]: 
first    A                       B                    
second   a           b           a           b        
third    1   2   3   1   2   3   1   2   3   1   2   3
0        0   1   2   3   4   5   6   7   8   9  10  11
1       12  13  14  15  16  17  18  19  20  21  22  23
2       24  25  26  27  28  29  30  31  32  33  34  35
3       36  37  38  39  40  41  42  43  44  45  46  47
4       48  49  50  51  52  53  54  55  56  57  58  59

In [109]: df.loc[:,idx[:,:,[2,3]]]-np.tile(df.loc[:,idx[:,:,1]].values,2)
Out[109]: 
first   A           B         
second  a     b     a     b   
third   2  3  2  3  2  3  2  3
0       1 -1 -2 -4  7  5  4  2
1       1 -1 -2 -4  7  5  4  2
2       1 -1 -2 -4  7  5  4  2
3       1 -1 -2 -4  7  5  4  2
4       1 -1 -2 -4  7  5  4  2
@mroeschke
Copy link
Member

Looks like this raises a specific ValueError now so it looks intentional that this shouldn't be supported I suppose. Closing but happy to reopen if I misunderstood

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment