gpt4 book ai didi

python - 为什么 pd.drop 在 for 循环外的功能与在 for 循环内的功能不同?

转载 作者:行者123 更新时间:2023-12-02 16:08:09 24 4
gpt4 key购买 nike

在单个数据帧上,我可以使用传统的 df = df.drop('column name') 删除列。但是,当我尝试遍历多个数据帧并将 drop() 应用于每个数据帧时,更改不会持久。我知道有一个我可以使用的 inplace='True' 参数,但我对 for 循环内部发生的基本情况感到困惑。

例子:

df_1 = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6]})
df_1
A B
0 1 4
1 2 5
2 3 6

df_2 = pd.DataFrame({'A':[10,20,30], 'C':[40,50,60]})
df_2
A C
0 10 40
1 20 50
2 30 60

# this is the behavior I am looking for.
df_1 = df_1.drop('A', axis=1)
df_1


B
0 4
1 5
2 6

# when I put 2 dataframes in a for loop, I do not get the same output.
df_1 = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6]})
df_2 = pd.DataFrame({'A':[10,20,30], 'C':[40,50,60]})
full_data = [df_1, df_2]

# I expect this code to apply the "drop" for each of these dataframes in the same way
# as above without the need for the "inplace" argument.
for dataset in full_data:
dataset = dataset.drop('A', axis=1)

# the column 'A' should have been dropped for each dataframe while inside the loop
# but it wasnt. why?
df_1
A B
0 1 4
1 2 5
2 3 6

最佳答案

该问题与特定的循环范围无关,而是一个基本的 python 分配规则问题。请参阅以下内容:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})

In [3]: another = df

In [4]: another is df
Out[4]: True

In [5]: another = another.drop('A', axis=1)

In [6]: another is df
Out[6]: False

在此示例中,您可以看到将删除操作的结果分配给 another 会将一个新对象分配给标识符 another。它不会就地修改 df 对象。另一方面,使用 inplace=True 关键字可以:

In [7]: another = df

In [8]: another.drop('A', axis=1, inplace=True)

In [9]: another is df
Out[9]: True

本质上,没有办法做您想做的事情,即遍历对象列表,然后通过使用循环标识符重新分配给变量来修改对象内容。 inplace=True 参数起作用的原因是它引用了数据帧本身的方法,让 pandas 控制结果的分配。

variables and object references 上查看这篇文章或更多信息。

关于python - 为什么 pd.drop 在 for 循环外的功能与在 for 循环内的功能不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68779533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com