Python 使用来自其他数据集的VLOOKUP更改pandas中的列名
让ee是具有以下列的数据集 我想将除Product_Code之外的所有列重命名为表4['Period']中相应的值。例如,“M20”列名称现在将为“2016/09”…'M53'现在将是'2019/06'Python 使用来自其他数据集的VLOOKUP更改pandas中的列名,python,pandas,merge,vlookup,Python,Pandas,Merge,Vlookup,让ee是具有以下列的数据集 我想将除Product_Code之外的所有列重命名为表4['Period']中相应的值。例如,“M20”列名称现在将为“2016/09”…'M53'现在将是'2019/06' 首先创建字典并将其传递给重命名: 或使用“按月索引”列通过系列: 样本: 抽取数据样本: ee.columns = ['Product Code','M20','M21'] Month Period 0 M20 2015/01 1 M21 2015/02 d = dict(zi
首先创建字典并将其传递给重命名: 或使用“按月索引”列通过系列: 样本:
抽取数据样本:
ee.columns = ['Product Code','M20','M21']
Month Period
0 M20 2015/01
1 M21 2015/02
d = dict(zip(ee.Month,ee.Period)) #creates a mapping dictionary
ee.columns=pd.Series(ee.columns).replace(d) #replaces where match found
#['Product Code', '2015/01', '2015/02']
也许您需要ee.columns=pd.seriese.columns。replaced@jezrael那将返回一个系列,不是吗?现在已更新代码:如果将其传递给列,则不需要转换为列表。
ee = ee.rename(columns=table4.set_index('Month')['Period'])
table4 = pd.DataFrame(
{'Month':['M0','M1','M2'],
'Period':['2015/01','2015/02','2015/03']})
print (table4)
Month Period
0 M0 2015/01
1 M1 2015/02
2 M2 2015/03
ee = pd.DataFrame(columns=['Product Code','M0','M2'])
ee = ee.rename(columns=dict(zip(table4['Month'], table4['Period'])))
print (ee)
Empty DataFrame
Columns: [Product Code, 2015/01, 2015/03]
Index: []
ee.columns = ['Product Code','M20','M21']
Month Period
0 M20 2015/01
1 M21 2015/02
d = dict(zip(ee.Month,ee.Period)) #creates a mapping dictionary
ee.columns=pd.Series(ee.columns).replace(d) #replaces where match found
#['Product Code', '2015/01', '2015/02']