python - 用条件参数替换Python中的DataFrame索引值

标签 python pandas dataframe

我正在尝试替换 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 来替换 indexcolumns 中的值。 :

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/

相关文章:

python - 基于两个单独列中的日期范围的总和

python - 如何在 pandas.to_latex() 生成的 LaTeX 表中自动换行文本?

python - 根据 Python 中的一个条件提取字符串数据框中的数字

python - 字典:如果列表中存在字符串,则将列表名称分配给字典

python - 使用 python 模块分发预构建的库

python - 如何在 Python 中将 IPv6 链路本地地址转换为 MAC 地址

python - 使用不在 pandas 中的向量化逻辑来过滤帧

r - 如何在 R 中的 ggplot 的一个图中绘制 2 个不同 y 轴上的两个列向量?

Python:计算数据框中列的减法

python - 在保持某些节点的连通性的条件下打破有向图中的循环