Alexis G
Alexis G

Reputation: 1339

Add index name to a dataframe / serie

I didn't know how I have to do for the following ! Has someone the solution ?

I have the following dataframe with TEST, DATE and PRODUCTS as indexes. I want to add a PRODUCTS as follow for all TEST and DATE. For example, T3 = T2 + 1

>>> df
TEST      DATE        PRODUCTS
A1        2014-02-28  T_01        7.9
                      T_1         8.1
                      T_2         8.6
          2014-03-03  T_01        7.4
                      T_1         8.4
                      T_2         8.7
...

And i want :

>>> df
TEST      DATE        PRODUCTS
A1        2014-02-28  T_01        7.9
                      T_1         8.1
                      T_2         8.7
                      T_3         9.6
          2014-03-03  T_01        7.4
                      T_1         8.4
                      T_2         8.7
                      T_3         9.7
...

Upvotes: 0

Views: 88

Answers (1)

CT Zhu
CT Zhu

Reputation: 54340

I think you can unstack it first, generate the T_3 and stack it back again.

In [15]:

print df
                            0
TEST DATE       PRODUCTS     
A1   2014-02-28 T_01      7.9
                T_1       8.1
                T_2       8.6
     2014-03-03 T_01      7.4
                T_1       8.4
                T_2       8.7

[6 rows x 1 columns]
In [16]:

df2 = df.unstack()[0] #if the variable name is 0
df2['T_3']=df2['T_2']+1
df2.stack() #need to convert to a DataFrame, 
Out[16]:
TEST  DATE        PRODUCTS
A1    2014-02-28  T_01        7.9
                  T_1         8.1
                  T_2         8.6
                  T_3         9.6
      2014-03-03  T_01        7.4
                  T_1         8.4
                  T_2         8.7
                  T_3         9.7
dtype: float64

Edit

The Alternative is to manually add the T_3 level:

In [37]:

df2=df.xs('T_2', level=2)+1
df2['PRODUCTS']='T_3'
df2.set_index('PRODUCTS', append=True, inplace=True)
df3=df.append(df2).sort_index()
In [38]:

print df3
                            0
TEST DATE       PRODUCTS     
A1   2014-02-28 T_01      7.9
                T_1       8.1
                T_2       8.6
                T_3       9.6
     2014-03-03 T_01      7.4
                T_1       8.4
                T_2       8.7
                T_3       9.7

[8 rows x 1 columns]

Upvotes: 1

Related Questions