gpt4 book ai didi

python - 如何重命名索引字符串?

转载 作者:行者123 更新时间:2023-12-01 03:03:50 25 4
gpt4 key购买 nike

我期待将索引名称“Juan Gonzalez”重命名为“Jason”,“Jorge Sanchez”重命名为“George”,“Miguel Sanz”重命名为“Michael”

                              age     height(cm)  weight(kg)
People
Juan Gonzalez               22     181    60
Jorge Sanchez          34     190     84
Miguel Sanz 50 166 59

我认为它在重命名列时就像:
df.rename(columns={,,}, inplace=True)

但是,当我尝试
df.rename(index={'Juan Gonzalez':'Jason','Jorge Sanchez':'George','Miguel Sanz':'Michael'}, inplace=True)

它不起作用,它返回具有相同索引名称的相同数据帧

最佳答案

索引值中似乎有一些空格。

要删除它,请使用 strip :

df.index = df.index.str.strip()

或添加参数 skipinitialspace=True read_csv .

sample :
import pandas as pd
from pandas.compat import StringIO

temp=u"""People,age height(cm),weight(kg)

Juan Gonzalez,22,181,60
Jorge Sanchez,34,190,84
Miguel Sanz,50,166,59"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp), skipinitialspace=True)
print (df)
People age height(cm) weight(kg)
Juan Gonzalez 22 181 60
Jorge Sanchez 34 190 84
Miguel Sanz 50 166 59

print (df.index)
Index(['Juan Gonzalez', 'Jorge Sanchez', 'Miguel Sanz'], dtype='object')

d = {'Juan Gonzalez':'Jason','Jorge Sanchez':'George','Miguel Sanz':'Michael'}
df.rename(index=d, inplace=True)
print (df)
People age height(cm) weight(kg)
Jason 22 181 60
George 34 190 84
Michael 50 166 59
import pandas as pd
from pandas.compat import StringIO

temp=u"""People,age height(cm),weight(kg)

Juan Gonzalez,22,181,60
Jorge Sanchez,34,190,84
Miguel Sanz,50,166,59"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp))
print (df)
People age height(cm) weight(kg)
Juan Gonzalez 22 181 60
Jorge Sanchez 34 190 84
Miguel Sanz 50 166 59

print (df.index)
Index([' Juan Gonzalez', ' Jorge Sanchez', 'Miguel Sanz'], dtype='object')

df.index = df.index.str.strip()

print (df.index)
Index(['Juan Gonzalez', 'Jorge Sanchez', 'Miguel Sanz'], dtype='object')

d = {'Juan Gonzalez':'Jason','Jorge Sanchez':'George','Miguel Sanz':'Michael'}
df.rename(index=d, inplace=True)
print (df)
People age height(cm) weight(kg)
Jason 22 181 60
George 34 190 84
Michael 50 166 59

关于python - 如何重命名索引字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43583572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com