简体   繁体   English

如何更改 dataframe 中的第一列名称

[英]how to change the first column name in dataframe

      first        second           third           fourth
1       9             2               0                7
0       4             3               2                1
3       4             0               4               -1
2       0             1               8               -5
       first       second           third           fourth
0       7             11              1               -7
3       2             5               5               -12
1       2             4               3                1
2      -3             7              -1                7

I have this data set in the panda data fame.我在 panda data fame 中有这个数据集。 I wonder about how can I change the value of the first column?(this is 2 different sets of data)我想知道如何更改第一列的值?(这是两组不同的数据)

ie list = ['abc','def','ghi','xyz'] i want this to replace those 0 1 2 3 in the first column in order respectively.即 list = ['abc','def','ghi','xyz'] 我希望它分别按顺序替换第一列中的那些 0 1 2 3。 I got something like this but it does not seem to work with multiple sets of data only work for one我得到了这样的东西,但它似乎不适用于多组数据只适用于一组

for i in range(4):
   df.rename(index={i: list[i]})

this is the error I got incase it may helps TypeError: unhashable type: 'list'这是我得到的错误,它可能有助于 TypeError: unhashable type: 'list'

PS I already sorted the data descending using the 'first' column so the index 0 1 2 3 is mixed up PS 我已经使用“第一”列对数据进行了降序排序,因此索引 0 1 2 3 混淆了

my expected out put would be something like我的预期输出会是这样的

first        second           third           fourth
def       9             2               0                7
abc       4             3               2                1
xyz       4             0               4               -1
ghi       0             1               8               -5
       first       second           third           fourth
abc       7             11              1               -7
xyz       2             5               5               -12
def       2             4               3                1
ghi      -3             7              -1                7

Use map使用map

d = dict(zip([0,1,2,3],['abc','def','ghi','xyz']))
df.index= df.index.map(d)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM