카테고리 없음

[파이썬] 한 번에 pandas 데이터 프레임의 여러 열에 함수를 적용하는 방법

행복을전해요 2021. 3. 1. 22:14

You can do df[['Col1', 'Col2', 'Col3']].applymap(format_number). Note, though that this will return new columns; it won't modify the existing DataFrame. If you want to put the values back in the original, you'll have to do df[['Col1', 'Col2', 'Col3']] = df[['Col1', 'Col2', 'Col3']].applymap(format_number).

-------------------

다음 apply과 같이 사용할 수 있습니다 .

df.apply(lambda row: format_number(row), axis=1)

format_number함수 에서 열을 지정해야 합니다.

def format_number(row):
    row['Col1'] = doSomething(row['Col1']
        row['Col2'] = doSomething(row['Col2'])
            row['Col3'] = doSomething(row['Col3'])
            

이것은 @BrenBarn의 대답만큼 우아하지는 않지만 데이터 프레임이 제자리에서 수정되어 열을 다시 할당 할 필요가 없다는 장점이 있습니다.



출처
https://stackoverflow.com/questions/22089829