我正在尝试替换 pandas 数据框中索引列中的一些字符串值。索引是国家/地区名称,我想将“英格兰及北爱尔兰联合王国”等字符串替换为“UK”。
数据框如下所示:
data = ['12','13','14', '15']
df = pd.DataFrame(data, index = ['Republic of Korea','United States of America20', 'United Kingdom of Great Britain and Northern Ireland19','China, Hong Kong Special Administrative Region'],columns=['Country'])
我已经尝试过:
d={"Republic of Korea": "South Korea",
"United States of America20": "United States",
"United Kingdom of Great Britain and Northern Ireland19": "United Kingdom",
"China, Hong Kong Special Administrative Region": "Hong Kong"}
df.index = df.index.str.replace(d)
不幸的是,我刚刚收到一条错误消息,指出替换缺少位置参数。
最佳答案
在 pandas 中,使用函数 rename
来替换 index
或 columns
中的值。 :
df = df.rename(d)
print (df)
Country
South Korea 12
United States 13
United Kingdom 14
Hong Kong 15
对我来说,时间几乎是相同的:
df = pd.concat([df] * 100000)
In [11]: %timeit df.rename(d)
10 loops, best of 3: 75.7 ms per loop
In [12]: %timeit pd.Series(df.index).replace(d)
10 loops, best of 3: 71.8 ms per loop
In [13]: %timeit pd.Series(df.index.values).replace(d)
10 loops, best of 3: 75.3 ms per loop
关于python - 用条件参数替换Python中的DataFrame索引值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47406231/