【问题标题】:How to replace specific values in columns only if it is the only one?只有当它是唯一的一个时,如何替换列中的特定值?
【发布时间】:2022-08-12 23:47:12
【问题描述】:

我有一个数据框:

id  val1                val2
1   \"he bought 0\"       \"0\"
2   \"0\"                 \"0-the student\"

我想将 0 替换为空(\"\"),但仅限于 \"0\" 的情况。所以例如“0-学生”不应该变成“-学生”。我怎么能这样做?期望的结果是:

id  val1                val2
1   \"he bought 0\"       \"\"
2   \"\"                 \"0-the student\"

str.replace(\"0\", \"\") 也会改变 \"0-the student\" 和 \"he buy 0\"

  • str.replace(\"^0$\", \"\") 应该可以工作 IIRC

标签: python python-3.x string dataframe replace


【解决方案1】:

你现在拥有的:

import pandas as pd
d = {'val1': ["he bought 0", "0"], 'val2': ["0", "0-the student"]}
df = pd.DataFrame(data=d)
print(df)

循环遍历每一列,然后是每一行。如果元素==“0”,替换为“”

for c, col in enumerate(d):
    for r, row in enumerate(d[col]):
        if row == "0":
            d[col][r] = ""
df = pd.DataFrame(data=d)
print(df)

【讨论】:

    【解决方案2】:

    你可以简单地:

    df[df == "0"] = ""
    

    【讨论】:

      猜你喜欢
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-15
      • 1970-01-01
      相关资源
      最近更新 更多