python - 更改 pandas 数据框中的索引值

标签 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], .....

最佳答案

您可以使用 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/

相关文章:

python - 基于所有列扩展窗口的Pandas qcut

python - 我们如何将函数应用于 pandas 和 python 中的整个组?

python - pandas - 用大写字母替换字符串中的一个字母

python - 使用带有opencv python的网络摄像头显示带有waitkey()的黑屏

python - 用其他列的值填充列中的空单元格

python - reshape pandas 数据框失败

python - 如何将 Period 字符串转换为实际的 Period 类型

python - 如何在动画粒子时与 mayavi 窗口交互? (在粒子群优化期间)

python - 我如何创建一个库作为 python 的一组通用导入

python - Google App Engine memcache.Client.cas() 因缺少 key 而不断返回 False