我正在分析一个形状类似于以下示例的数据集.我有两种不同类型的数据(abc数据和xyz数据):
abc1 abc2 abc3 xyz1 xyz2 xyz3
0 1 2 2 2 1 2
1 2 1 1 2 1 1
2 2 2 1 2 2 2
3 1 2 1 1 1 1
4 1 1 2 1 2 1
Run Code Online (Sandbox Code Playgroud)
我想创建一个函数,为数据框中存在的每个abc列添加一个分类列.使用列名列表和类别映射字典,我能够得到我想要的结果.
abc_columns = ['abc1', 'abc2', 'abc3']
xyz_columns = ['xyz1', 'xyz2', 'xyz3']
abc_category_columns = ['abc1_category', 'abc2_category', 'abc3_category']
categories = {1: 'Good', 2: 'Bad', 3: 'Ugly'}
for i in range(len(abc_category_columns)):
df3[abc_category_columns[i]] = df3[abc_columns[i]].map(categories)
print …Run Code Online (Sandbox Code Playgroud)