如何更改 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], .....
请您参考如下方法:
您可以使用 astype 将索引转换为 str 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])
