为什么不能遍历 pandas 数据帧?

问题描述 投票:0回答:5

假设有几个相似的数据帧要对其执行操作,例如删除或重命名列。人们可能想循环进行:

this = pd.DataFrame({'text': ['Hello World']})
that = pd.DataFrame({'text': ['Hello Gurl']})

for df in [this, that]:
    df = df.rename(columns={'text': 'content'})

没有异常,但是数据帧保持不变。为什么会这样,我怎样才能遍历数据帧而不必多次键入同一行代码?

另一方面,创建新列等操作确实有效:

for df in [this, that]:
    df['content'] = df.text
python pandas dataframe loops iteration
5个回答
1
投票

实际上可以迭代 pandas 数据帧,但提供的代码中的问题是由于重命名或删除列在默认情况下不会就地操作。因此,

df = df.rename(columns={'text': 'content'})
行创建了一个包含修改后的列的新数据框,但不修改原始数据框。

要修改原来的dataframes,可以修改代码如下:

this = pd.DataFrame({'text': ['Hello World']})
that = pd.DataFrame({'text': ['Hello Gurl']})
for df in [this, that]:
    df.rename(columns={'text': 'content'}, inplace=True)

这里加入

inplace=True
参数,直接修改原始dataframes

或者,修改后的数据框可以保存在列表或字典中:

this = pd.DataFrame({'text': ['Hello World']})
that = pd.DataFrame({'text': ['Hello Gurl']})
dfs = []
for df in [this, that]:
    dfs.append(df.rename(columns={'text': 'content'}))  # save modified dataframe in list
    
# OR using dictionary
new_dfs = {}
for key, df in [('this', this), ('that', that)]:
    new_dfs[key] = df.rename(columns={'text': 'content'})  # save modified dataframe in dictionary

然后可以从列表或字典访问修改后的数据框。


0
投票

.rename()
调用
inplace=True
让它修改 DF 本身。

this = pd.DataFrame({'text': ['Hello World']})
that = pd.DataFrame({'text': ['Hello Gurl']})

for df in [this, that]:
    df.rename(columns={'text': 'content'}, inplace=True)

至于“为什么不修改”,它类似于,说,

this = ("foo",)
that = ("bar",)

for x in (this, that):
    x = x + ("blarp",)

不分配

("foo", "blarp")
("bar", "blarp")
回到
this
that
.


0
投票

因为

df.rename
返回一个新的数据框。 pandas的很多函数也是如此。添加
inplace=true

for df in [this, that]:
    df.rename(columns={'text': 'content'}, inplace=True)

0
投票

如果你想就地重命名你的列,你可以使用

rename
方法以
inplace=True
作为参数,但你也可以直接重命名
Index
因为它不是返回副本的方法:

d = {'text': 'content'}

for df in [this, that]:
    df.columns = [d.get(col, col) for col in df.columns]

输出:

>>> this
       content
0  Hello World

>>> that
      content
0  Hello Gurl

0
投票

正如其他答案所提到的,

rename
返回一个副本,并且原始 DataFrame 没有改变。而且由于您正在动态创建一个临时列表,因此一旦循环完成就无法恢复更新的结果。

inplace=True
在我看来是有害的
.

所以不要使用它。一些答案建议使用列表/字典,对您的代码进行一些小改动:

dfs = [this, that]
for i in range(len(dfs)):
    dfs[i] = dfs[i].rename(...) # do something with dfs[i] and assign it back
# unpack the result
this, that = dfs

这是有效的,因为

rename
操作的结果被分配回您引用的列表。

© www.soinside.com 2019 - 2024. All rights reserved.