change index value in pandas dataframe
<p>How can I change the value of the index in a pandas dataframe?</p>

<p>for example, from this:</p>

<pre><code>In[1]:plasmaLipo
Out[1]: 
         Chyloquantity  ChyloSize  VLDLquantity  VLDLSize  LDLquantity  \
Sample                                                                 
1010107          1.07       87.0         115.0      38.7        661.0   
1020107          1.13       88.0         119.0      38.8        670.0   
1030107          0.66       87.0         105.0      37.7        677.0   
1040107          0.74       88.0         100.0      38.1        687.0   
...
</code></pre>

<p>to this:</p>

<pre><code>In[1]:plasmaLipo
Out[1]: 
         Chyloquantity  ChyloSize  VLDLquantity  VLDLSize  LDLquantity  \
Sample                                                                 
1010             1.07       87.0         115.0      38.7        661.0   
1020             1.13       88.0         119.0      38.8        670.0   
1030             0.66       87.0         105.0      37.7        677.0   
1040             0.74       88.0         100.0      38.1        687.0   
...
</code></pre>

<p>i.e. use only the first 4 digits of the index.</p>

<p>I tried to convert the index in a list and then modify it:</p>

<pre><code>indx = list(plasmaLipo.index.values)
newindx = []
for items in indx:
    newindx.append(indx[:3])
print newindx
</code></pre>

<p>but gives me back the first 3 elements of the list:</p>

<pre><code>Out[2] [[1010101, 1020101, 1030101], [1010101, 1020101, 1030101], .....
</code></pre>

<p>You can convert the index to <code>str</code> dtype using <code>astype</code> and then slice the string values, cast back again using <code>astype</code> and overwrite the index attribute:</p>

<pre><code>In [30]:
df.index = df.index.astype(str).str[:4].astype(int)
df

Out[30]:
        Chyloquantity  ChyloSize  VLDLquantity  VLDLSize  LDLquantity
Sample                                                               
1010             1.07       87.0         115.0      38.7        661.0
1020             1.13       88.0         119.0      38.8        670.0
1030             0.66       87.0         105.0      37.7        677.0
1040             0.74       88.0         100.0      38.1        687.0
</code></pre>

<p>what you tried:</p>

<pre><code>for items in indx:
    newindx.append(indx[:3])
</code></pre>

<p>looped over each index value in <code>for items in indx</code> but you then appended a slice of the entire index on the next line <code>newindx.append(indx[:3])</code> which is why it repeated the first 3 index values for each index item</p>

<p>it would've worked if you did:</p>

<pre><code>for items in indx:
    newindx.append(items[:3])
</code></pre>

python pandas