更改pandas数据框

时间:2016-09-16 14:36:21

标签: python pandas

如何在pandas数据框中更改索引的值?

例如,来自:

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   
...

到此:

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   
...

即。仅使用索引的前4位数字。

我尝试在列表中转换索引然后修改它:

indx = list(plasmaLipo.index.values)
newindx = []
for items in indx:
    newindx.append(indx[:3])
print newindx

但是让我回到了列表的前3个元素:

Out[2] [[1010101, 1020101, 1030101], [1010101, 1020101, 1030101], .....

1 个答案:

答案 0 :(得分:2)

您可以使用str将索引转换为astype dtype,然后对字符串值进行切片,使用astype再次强制转换并覆盖索引属性:

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

你尝试了什么:

for items in indx:
    newindx.append(indx[:3])

循环遍历for items in indx中的每个索引值,但是您在下一行newindx.append(indx[:3])上附加了整个索引的一部分,这就是为什么它重复了每个索引项的前3个索引值

如果你这样做,它会起作用:

for items in indx:
    newindx.append(items[:3])