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

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

10-04 21:44
查看更多