죄송합니다. 어리석은 짓을하고 있지만이 문제로 인해 매우 혼란 스럽습니다. DataFrame을 함수에 전달하고 해당 함수 내부에 열을 추가하고 놓습니다. 여기까지는 이상한 것은 없지만 함수가 끝나면 전역 이름 스코프의 DataFrame에 추가 된 & 열이 표시됩니다. DF를 전역으로 선언하면 ...이 문제는 발생하지 않습니다.pandas DataFrame이 다시 나타나는 열
이 테스트 코드는 Python 3.3.3/2.7.6과 pandas 0.13.0/0.12의 조합으로 인해 발생한 4 가지 경우의 문제를 보여줍니다. 0.0 :
#!/usr/bin/python
import pandas as pd
# FUNCTION DFcorr
def DFcorr(df):
# Calculate column of accumulated elements
df['SUM']=df.sum(axis=1)
print('DFcorr: DataFrame after add column:')
print(df)
# Drop column of accumulated elements
df=df.drop('SUM',axis=1)
print('DFcorr: DataFrame after drop column:')
print(df)
# FUNCTION globalDFcorr
def globalDFcorr():
global C
# Calculate column of accumulated elements
C['SUM']=C.sum(axis=1)
print('globalDFcorr: DataFrame after add column:')
print(C)
# Drop column of accumulated elements
print('globalDFcorr: DataFrame after drop column:')
C=C.drop('SUM',axis=1)
print(C)
######################### MAIN #############################
C = pd.DataFrame.from_items([('A', [1, 2]), ('B', [3 ,4])], orient='index', columns['one', 'two'])
print('\nMAIN: Initial DataFrame:')
print(C)
DFcorr(C)
print('MAIN: DataFrame after call to DFcorr')
print(C)
C = pd.DataFrame.from_items([('A', [1, 2]), ('B', [3 ,4])], orient='index', columns=['one', 'two'])
print('\nMAIN: Initial DataFrame:')
print(C)
globalDFcorr()
print('MAIN: DataFrame after call to globalDFcorr')
print(C)
을 그리고 여기 당신이 출력됩니다 : 나는 무엇을
MAIN: Initial DataFrame:
one two
A 1 2
B 3 4
[2 rows x 2 columns]
DFcorr: DataFrame after add column:
one two SUM
A 1 2 3
B 3 4 7
[2 rows x 3 columns]
DFcorr: DataFrame after drop column:
one two
A 1 2
B 3 4
[2 rows x 2 columns]
MAIN: DataFrame after call to DFcorr
one two SUM
A 1 2 3
B 3 4 7
[2 rows x 3 columns]
MAIN: Initial DataFrame:
one two
A 1 2
B 3 4
[2 rows x 2 columns]
globalDFcorr: DataFrame after add column:
one two SUM
A 1 2 3
B 3 4 7
[2 rows x 3 columns]
globalDFcorr: DataFrame after drop column:
one two
A 1 2
B 3 4
[2 rows x 2 columns]
MAIN: DataFrame after call to globalDFcorr
one two
A 1 2
B 3 4
[2 rows x 2 columns]
를 놓친 거지? 많은 감사합니다!
감사 :
그래서, 당신에게 그 라인을 변경하여
globalDFcorr
처럼DFcorr
행동하라 더 만들 수 있습니다. 그런 다음 함수 범위 (이 경우'df')에서 DataFrame 식별자를 사용할 때 전역 변수 또는 로컬 변수를 임의로 참조 할 수 있다는 것을 이해해야합니까? 나는 대답에서 'df ['SUM '] = df.sum (축 = 1)'df가 전역 변수에 영향을 미치고있는 동안 df = df.drop ('SUM ' , axis = 1)''print (df)'에서'df'가 지역 변수를 참조하고 있습니까? – khyox나는 내가 내 대답을 제대로 이해했는지 확인할 수 있도록 내 추론을하자. C/C++ 포인터로'df'에서 생각하면 호출 된 함수의 시작 부분에 전역 범위의 DataFrame을 가리킨다. 'df = 'SUM'= df.sum (축 = 1)'을 할 때 'C'를 너무 참고하지만,'df = df.drop ('SUM', axis = 1)'이면,'df'는 함수의 로컬 인 새로운 DataFrame을 가리키게됩니다. 이 추론은 옳은가? 많은 감사합니다. – khyox
@khyox : 네, 가지고 있다고 생각합니다! 다음은 파이썬의 [패배 할당] (http://stackoverflow.com/a/8140747/190597) 함수 패러다임 호출에 대한 설명입니다. – unutbu