我有一个数据框
df=pd.DataFrame({'name':['a','b','c','a','b','a'],'value':\
[1,2,3,4,5,6],'value2':[7,8,9,10,11,12]})
我想将列名称映射到新列表,例如:['G','H','F'],所以我会得到:
df=pd.DataFrame({'name':['G','H','F','G','H','G'],'value':\
[1,2,3,4,5,6],'value2':[7,8,9,10,11,12]})
答案 0 :(得分:2)
使用内置的pandas
方法:
>>> df=pd.DataFrame({'name':['a','b','c','a','b','a'],'value':\
... [1,2,3,4,5,6],'value2':[7,8,9,10,11,12]})
>>> df
name value value2
0 a 1 7
1 b 2 8
2 c 3 9
3 a 4 10
4 b 5 11
5 a 6 12
>>> df.name.map({'a':'G','b':'H','c':'F'})
0 G
1 H
2 F
3 G
4 H
5 G
Name: name, dtype: object
>>> df['name'] = df.name.map({'a':'G','b':'H','c':'F'})
>>> df
name value value2
0 G 1 7
1 H 2 8
2 F 3 9
3 G 4 10
4 H 5 11
5 G 6 12
>>>
答案 1 :(得分:0)
制作一个词典:
mapping = {'a':'G', 'b':'H', 'c':'F'}
然后:
df['name'] = [mapping[item] for item in df['name']]