如何更改熊猫数据框中的索引值?
例如,从此:
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], .....
您可以使用将索引转换为str
dtype astype
,然后切片字符串值,使用astype
并再次覆盖并覆盖index属性:
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])
这就是为什么它为每个索引项重复前三个索引值的原因
如果您这样做,它会起作用:
for items in indx:
newindx.append(items[:3])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句