如何使用apply函数在pandas数据框中重命名列?

时间:2019-04-15 08:56:40

标签: python pandas

我想重命名pandas数据框中的一列。我想通过使用apply函数来做到这一点。我编写了一个代码来执行此操作,但是我不知道如何使用apply fucntion来执行此操作。有人可以帮忙吗?

import pandas as pd
import numpy as np
import datetime

url = 'https://raw.githubusercontent.com/lukes/ISO-3166-Countries-with-Regional-Codes/master/all/all.csv'
df_github = pd.read_csv(url)

df_github  = df_github.rename(columns={'name':'Country'})

2 个答案:

答案 0 :(得分:0)

可能,但过于复杂,因为需要将索引转换为序列,然后使用lambda调用apply函数:

d = {'name':'Country'}
df_github.columns  = df_github.columns.to_series().apply(lambda x: d.get(x, x))

答案 1 :(得分:0)

我同意jezrael,这只会使它不必要地复杂。如果您真的想使用apply(显然与jezrael的解决方案非常相似),那么这就是我将其作为“快速而肮脏的”解决方案的方式:

df_github.columns = df_github.columns.to_series().apply(lambda x: 'Country' if x == 'name' else x )