简体   繁体   English

Pandas 替换在一行中有效,但在另一行中无效

[英]Pandas replace works in one line, but not in another

I'm trying to clean some data (Python 3.7.3) and was able to replace NaN values with empty strings using我正在尝试清理一些数据(Python 3.7.3)并且能够使用空字符串替换 NaN 值

def g(x):
    return pd.Series(x.replace(np.nan, ""))
df = df.apply(g)

and get the desired output:并获得所需的 output:

1    2      3            4
qt>  qml>   tableview>

etc, but then I tried to do something similar to replace the ">" with an empty string等等,但后来我尝试做类似的事情来用空字符串替换“>”

def h(x):
   return pd.Series(x.replace(">", ""))
df = df.apply(h)

but the dataframe doesn't change and I still have the ">" at the end of each word.但是 dataframe 没有改变,我仍然在每个单词的末尾都有“>”。 No errors are thrown at me, so I'm at a loss.没有错误发生在我身上,所以我很茫然。 Thanks in advance for any answers提前感谢您的任何答案

Replace your h function with:将您的h function 替换为:

def h(x):
   return pd.Series(x.str.replace(">", ""))
df = df.apply(h)
def h(x):
      return x.replace(">", "",regex=True)
df = df.apply(h)

Please try the following:请尝试以下方法:

def g(x):
    return pd.Series(x.replace(">", "",regex=True))
df = df.apply(g)  

This should work.这应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM