簡體   English   中英

如何在Data Frame Python中獲取除一列之外的所有列?

[英]How to take all columns except one column in Data Frame Python?

我有例如 24 列的 DataFrame,我的問題是如何獲取除列號 17 之外的所有列?

data[:,:]使用這種語法。

你可以這樣做:

data.drop(columns=['a']) # for column name
data.drop(columns=data.columns[17]) # for column index

它返回一個您可以使用的dataframe

更多信息: pandas drop

您可以使用np.r_df.iloc下面像基於位置索引與切片:

pos_of_col= 17
df.iloc[:,np.r_[range(pos_of_col-1),range(pos_of_col,len(df.columns))]]

Demo ,刪除位置 4 的列(第 3 列,因為 Python 索引從 0 開始)

np.random.seed(0)
df = pd.DataFrame(np.random.randint(0,20,(5,10))).add_prefix("col_")
print(df,'\n')

pos_of_col= 4
print(df.iloc[:,np.r_[range(pos_of_col-1),range(pos_of_col,len(df.columns))]])



   col_0  col_1  col_2  col_3  col_4  col_5  col_6  col_7  col_8  col_9
0     12     15      0      3      3      7      9     19     18      4
1      6     12      1      6      7     14     17      5     13      8
2      9     19     16     19      5     15     15      0     18      3
3     17     19     19     19     14      7      0      1      9      0
4     10      3     11     18      2      0      0      4      5      6 

   col_0  col_1  col_2  col_4  col_5  col_6  col_7  col_8  col_9
0     12     15      0      3      7      9     19     18      4
1      6     12      1      7     14     17      5     13      8
2      9     19     16      5     15     15      0     18      3
3     17     19     19     14      7      0      1      9      0
4     10      3     11      2      0      0      4      5      6

我認為更簡單的方法是:

data.loc[:, data.columns != 'col_name']

或者

data.loc[:, ~data.columns.isin(['col_name'])]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM