gpt4 book ai didi

python - 更改 Pandas 列中的类别?

转载 作者:行者123 更新时间:2023-12-01 09:03:02 25 4
gpt4 key购买 nike

我正在 pandas 上尝试 iter 函数。

1-我从 pandas 列中制作了一个列表。

in1:

df_area_code_iter = iter(df["Area Code"])
df_area_code_iter_list = list(df_area_code_iter)
df_area_code_iter_list

out_1:

['Area 1',
'Area 2',
'Area 1',
...
'Area 0']

2- 然后我想遍历列表的元素,用 PASS THIS 替换 Area 0。

in_2:

new_column = []

for i in df_area_code_iter_list:
if i == "Area 0":
i == "PASS THIS"
new_column.append(i)

new_column

out_2:

['Area 1',
'Area 2',
'Area 1',
...
'Area 0']

我知道还有其他方法可以替换列中的值。但是,我想通过将数据帧转换为列表然后迭代元素来解决这个问题。

in_3:

df["Area Code"] = df["Area Code"].replace(to_replace ="Area 0", value = 
"PASS THIS")
df["Area Code"]

out_3:

0          Area 1
1 Area 2
2 Area 1
3 Area 1
4 PASS THIS
5 PASS THIS
6 PASS THIS
... ....

正如我所说,我正在试验,但我看不出有任何原因可以解释为什么 in_2 处的 for 循环不起作用。

最佳答案

主要问题是赋值需要=,而不是相等运算符==

您被迫附加到新列表,因为循环内的变量i是标量,而不是指向原始列表中元素的引用。相反,您可以使用 enumerate 并修改现有列表:

for idx, val in enumerate(df_area_code_iter_list):
if val == "Area 0":
df_area_code_iter_list[idx] = "PASS THIS"

或者,更Pythonic,使用列表理解:

new_list = [x if x != 'Area 0' else 'PASS THIS' for x in df_area_code_iter_list]

关于python - 更改 Pandas 列中的类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52310755/

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