简体   繁体   English

在for循环中删除列-Pandas

[英]Dropping column during for loop - Pandas

I have two basic DataFrames, and I combine them into a list called dfCombo: 我有两个基本的DataFrame,并将它们组合到一个名为dfCombo的列表中:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(12).reshape(3,4), columns=['A', 'B', 'C', 'D'])
df2 = pd.DataFrame(np.arange(12,24).reshape(3,4), columns=['A', 'B', 'C', 'D'])
dfCombo = [df, df2]

They are both 3x4 DF's with 4 columns A, B, C, D. 它们都是具有4列A,B,C,D的3x4 DF。

I am able to use a for loop to add a column to both the DF with the following code: 我可以使用for循环通过以下代码将列添加到DF中:

for df3 in dfCombo:
    df3['E'] = df3['A'] + df3['B']

With this both df and df2 will both have an new column E. However when I try to drop a column using this method with the below code, no columns are dropped: 与此同时,df和df2都将具有新的列E。但是,当我尝试使用以下代码使用此方法删除列时,不会删除任何列:

for df3 in dfCombo:
    df3 = df3.drop('B', axis = 1)

or 要么

for df3 in dfCombo:
    df3 = df3.drop(columns = ['B'])

If I use the same code on a single DF the column is dropped: 如果我在单个DF上使用相同的代码,则会删除该列:

df2 = df2.drop('B', axis = 1)

or 要么

df2 = df2.drop(columns = ['B'])

If you could help me understand what is going on I would be most appreciative. 如果您能帮助我了解正在发生的事情,我将非常感激。

You need to use inplace=True : 您需要使用inplace=True

for df3 in dfCombo:
    df3.drop('B', axis = 1, inplace=True)

Which returns: 哪个返回:

   A   C   D   E
0  0   2   3   1
1  4   6   7   9
2  8  10  11  17

    A   C   D   E
0  12  14  15  25
1  16  18  19  33
2  20  22  23  41

The default inplace=False is intended for assigning back to the original dataframe, because it returns a new copy. 默认的inplace=False用于分配回原始数据帧,因为它返回一个新副本。 However inplace=True operates on the same copy and returns None , therefore there is no need to assign back to the original dataframe. 但是inplace=True在同一副本上操作并返回None ,因此无需分配回原始数据帧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM