python dataframe pandas在中放置列

2024-04-25 02:16:30 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

像这样放置多个列:

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”)。

您可以删除i索引上的列,如下所示:

df.drop(df.columns[i], axis=1)

如果在列中有重复的名称,那么它可能工作得很奇怪,为此,可以按新名称重命名要删除的列。或者您可以这样重新分配数据帧:

df = df.iloc[:, [j for j, c in enumerate(df.columns) if j != i]]

相关问题 更多 >