int를 사용하여 python dataframe pandas drop column
열을 삭제하려면 df.drop ( 'column name', axis = 1)을 사용합니다. 열 이름 대신 숫자 색인을 사용하여 열을 삭제하는 방법이 있습니까?
다음 i
과 같이 인덱스에서 열을 삭제할 수 있습니다 .
df.drop(df.columns[i], axis=1)
열에 중복 이름이 있으면 이상하게 작동 할 수 있으므로 삭제하려는 열의 이름을 새 이름으로 바꿀 수 있습니다. 또는 다음과 같이 DataFrame을 다시 할당 할 수 있습니다.
df = df.iloc[:, [j for j, c in enumerate(df.columns) if j != i]]
다음과 같이 여러 열을 삭제하십시오.
cols = [1,2,4,5,12]
df.drop(df.columns[cols],axis=1,inplace=True)
inplace=True
데이터 프레임 사본에서 열을 삭제하지 않고 데이터 프레임 자체를 변경하는 데 사용됩니다. 원본을 그대로 유지하려면 다음을 사용하십시오.
df_after_dropping = df.drop(df.columns[cols],axis=1)
동일한 이름을 가진 여러 열이있는 경우 여기에 제공된 솔루션은 모든 열을 제거하므로 원하는 열이 아닐 수 있습니다. 하나의 인스턴스를 제외한 중복 열을 제거하려는 경우에 해당됩니다. 아래 예제는이 상황을 명확하게합니다.
# make a df with duplicate columns 'x'
df = pd.DataFrame({'x': range(5) , 'x':range(5), 'y':range(6, 11)}, columns = ['x', 'x', 'y'])
df
Out[495]:
x x y
0 0 0 6
1 1 1 7
2 2 2 8
3 3 3 9
4 4 4 10
# attempting to drop the first column according to the solution offered so far
df.drop(df.columns[0], axis = 1)
y
0 6
1 7
2 8
3 9
4 10
보시다시피, 두 Xs 열이 모두 삭제되었습니다. 대체 솔루션 :
column_numbers = [x for x in range(df.shape[1])] # list of columns' integer indices
column_numbers .remove(0) #removing column integer index 0
df.iloc[:, column_numbers] #return all columns except the 0th column
x y
0 0 6
1 1 7
2 2 8
3 3 9
4 4 10
보시다시피, 이것은 실제로 0 번째 열 (첫 번째 'x') 만 제거했습니다.
데이터 프레임에서의 위치를 기준으로 열을 식별해야합니다. 예를 들어, 열 번호 2, 3 및 5를 삭제 (del)하려는 경우,
df.drop(df.columns[[2,3,5]], axis = 1)
정말로 정수로 (하지만 왜?) 그것을하고 싶다면 사전을 만들 수 있습니다.
col_dict = {x: col for x, col in enumerate(df.columns)}
다음 df = df.drop(col_dict[0], 1)
원하는대로 작동합니다
편집 : 당신을 위해 그것을 할 수있는 함수에 넣을 수 있습니다.
def drop_col_n(df, col_n_to_drop):
col_dict = {x: col for x, col in enumerate(df.columns)}
return df.drop(col_dict[col_n_to_drop], 1)
df = drop_col_n(df, 2)
You can use the following line to drop the first two columns (or any column you don't need):
df.drop([df.columns[0], df.columns[1]], axis=1)
Since there can be multiple columns with same name , we should first rename the columns. Here is code for the solution.
df.columns=list(range(0,len(df.columns)))
df.drop(columns=[1,2])#drop second and third columns
참고URL : https://stackoverflow.com/questions/20297317/python-dataframe-pandas-drop-column-using-int
'Programing' 카테고리의 다른 글
문자열이 아닌 숫자로 CSS 최고 값을 얻으시겠습니까? (0) | 2020.07.21 |
---|---|
HTML / css로 Chrome / Safari 맞춤법 검사 기능 끄기 (0) | 2020.07.21 |
MVC에서 PDF를 브라우저로 반환하는 방법은 무엇입니까? (0) | 2020.07.21 |
다른 UIView에서 UIView와의 상호 작용 허용 (0) | 2020.07.21 |
start-stop-daemon으로 시작한 프로세스의 stdout을 어떻게 기록 할 수 있습니까? (0) | 2020.07.21 |