如何更改 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 indx中的项目
中的每个索引值,但随后在下一行附加整个索引的切片newwindx.append(indx[:3])
这就是为什么它为每个索引项重复前 3 个索引值
如果你这样做就会成功:
for items in indx:
newindx.append(items[:3])
关于python - 更改 pandas 数据框中的索引值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39534129/