해당 열 중 하나에 함수를 적용하고 동일한 열에 결과를 할당하려는 MultiIndex pandas DataFrame이 있습니다. 나는이 경고를 얻을 수 있기 때문에 당신이 볼 수 있듯이MultiIndex pandas.DataFrame 열에 함수 적용
In [1]:
import numpy as np
import pandas as pd
cols = ['One', 'Two', 'Three', 'Four', 'Five']
df = pd.DataFrame(np.array(list('ABCDEFGHIJKLMNO'), dtype='object').reshape(3,5), index = list('ABC'), columns=cols)
df.to_hdf('/tmp/test.h5', 'df')
df = pd.read_hdf('/tmp/test.h5', 'df')
df
Out[1]:
One Two Three Four Five
A A B C D E
B F G H I J
C K L M N O
3 rows × 5 columns
In [2]:
df.columns = pd.MultiIndex.from_arrays([list('UUULL'), ['One', 'Two', 'Three', 'Four', 'Five']])
df['L']['Five'] = df['L']['Five'].apply(lambda x: x.lower())
df
-c:2: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
Out[2]:
U L
One Two Three Four Five
A A B C D E
B F G H I J
C K L M N O
3 rows × 5 columns
In [3]:
df.columns = ['One', 'Two', 'Three', 'Four', 'Five']
df
Out[3]:
One Two Three Four Five
A A B C D E
B F G H I J
C K L M N O
3 rows × 5 columns
In [4]:
df['Five'] = df['Five'].apply(lambda x: x.upper())
df
Out[4]:
One Two Three Four Five
A A B C D E
B F G H I J
C K L M N O
3 rows × 5 columns
, 함수가 열에 적용되지 않는 것 같아요 :
-c:2: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
어떤 이상한 것은이 오류는 종종 발생, 나는 천국이다 그 일이 언제 언제 일어나는지를 이해할 수 없었습니다. 경고가 권장하는
나는.loc
으로 dataframe 슬라이스 기능을 적용 할 관리 :
In [5]:
df.columns = pd.MultiIndex.from_arrays([list('UUULL'), ['One', 'Two', 'Three', 'Four', 'Five']])
df.loc[:,('L','Five')] = df.loc[:,('L','Five')].apply(lambda x: x.lower())
df
Out[5]:
U L
One Two Three Four Five
A A B C D e
B F G H I j
C K L M N o
3 rows × 5 columns
을하지만이 동작이 DICT 같은 슬라이스를 수행 할 때 발생하는 이유를 이해하고자하는 (예를 들어 df['L']['Five']
을)와하지 않을 때 .loc
슬라이싱을 사용합니다.
참고 : DataFrame은 멀티 인덱싱되지 않은 HDF 파일에서 가져온 것일 수 있습니다. 이것은 아마 이상한 동작의 원인입니까?
EDIT : 나는 값이 'L'다음 열의 다섯 '가 선택되는 DataFrame를 반환하는 액세스 시리즈 복귀 가진 레벨 0을 선택한다 Pandas v.0.13.1
및
정말이 설명이 마음에 들었습니다 ... 우리가 문서에서 비슷한 것을 알고 있지만이 책은 더 좋은 산문을 가지고 있습니다. 'pd.merge (orig_doc, this_explanation, how = 'right')'를 할 수 있을까요? :) –
업데이트 : http://pandas-docs.github.io/pandas-docs-travis/indexing.html#returning-a-view-versus-a-copy – Jeff