gpt4 book ai didi

python - 将 pandas 数据框中的词汇表更改为值 "1"

转载 作者:太空宇宙 更新时间:2023-11-03 15:04:51 25 4
gpt4 key购买 nike

我有以下数据框。我要将 ADR 中的所有值替换为值 1。Th

Index    ADR
1 Fair
2 good
3 best
4 tr
5 heavy

这是我的代码:

df1['ADR'] = df1.replace(r'\w+', 1, regex=True)
df1['ADR'] = df1.replace(r'\w+',r'\ 1', regex=True)

但是他们都创建了以下数据集:

  Index    ADR
1 1
2 2
3 3
4 4
5 5

我需要 ADR 中的所有值都为“1”。这是所需的输出。

  Index    ADR
1 1
2 1
3 1
4 1
5 1

有什么建议吗?

最佳答案

您需要指定替换ADR的列:

df1['ADR'] = df1['ADR'].replace(r'\w+', 1, regex=True)
print (df1)
Index ADR
0 1 1
1 2 1
2 3 1
3 4 1
4 5 1

另一种解决方案是用 dict 指定列来替换:

df1 = df1.replace({'ADR':{ r'\w+': 1}}, regex=True)
print (df1)
Index ADR
0 1 1
1 2 1
2 3 1
3 4 1
4 5 1

但如果需要与指定的所有值相同的 John Galt ,则更好的是分配标量:

df1['ADR'] = 1
print (df1)
Index ADR
0 1 1
1 2 1
2 3 1
3 4 1
4 5 1

关于python - 将 pandas 数据框中的词汇表更改为值 "1",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44762302/

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