2017-02-18 1 views
2

나는 다음과 같은 팬더 dataframe이 : 나는 (예를 들어, 01nn에) ID로 모든 과일을 대체하고 싶은팬더 데이터 프레임의 값을 바꾸는 중 문제가 발생 했습니까?

Fruits 
0 this should be a pinneapple 
1 this should be an apple 
2 this should be a tomato 
3 this should 3 grapes 
4 this should be an orange 
5 this should be an 01 
6 this should be an 02 

:에서

:

df = pd.DataFrame({'Fruits':['this should be a pinneapple', 
           'this should be an apple', 
           'this should be a tomato', 'this should 3 grapes', 
          'this should be an orange', 
           'this should be an 01', 
          'this should be an 02']}) 

df 

아웃. 내가 팬더와 노력이이 기능을 대체 할 경우 : 나는 위의 할당 아무것도 컬럼에 수행되지 않습니다 수행 할 때

df['Fruits'] = df['Fruits'].replace(['pinneapple', 'apple', 'tomato', 'grapes', 'orange'],\ 
                     ['01', '02', '03', '04', '05']) 

는 그러나, 나는 조정할에 관심이 있습니다. 따라서, 어떻게 미리 정의 된 번호에 대한 각 단어를 바꿀 수 있습니까?.

답변

3

당신은 Series.replace에서 매개 변수 regex=True를 사용할 수 있습니다

df['Fruits'] = df['Fruits'].replace(['pinneapple', 'apple', 'tomato', 'grapes', 'orange'],\ 
            ['01', '02', '03', '04', '05'], regex=True) 
print (df) 
       Fruits 
0 this should be a 01 
1 this should be an 02 
2 this should be a 03 
3  this should 3 04 
4 this should be an 05 
5 this should be an 01 
6 this should be an 02 

또한 사용할 수 있습니다 list comprehensioncodes을 위해 : 다음

df['Fruits'] = pd.DataFrame() 

:

fruits = ['pinneapple', 'apple', 'tomato', 'grapes', 'orange'] 
codes = [str(i + 1).zfill(2) for i, c in enumerate(fruits)] 
print (codes) 
['01', '02', '03', '04', '05'] 

df['Fruits'] = df['Fruits'].replace(fruits,codes, regex=True) 
print (df) 

       Fruits 
0 this should be a 01 
1 this should be an 02 
2 this should be a 03 
3  this should 3 04 
4 this should be an 05 
5 this should be an 01 
6 this should be an 02 
+0

도움 주셔서 감사합니다. – tumbleweed

1

다음 사용하여 값을 재설정 해보십시오 새 값을 다시 할당하십시오.

관련 문제