Data frame indexing not working as it should be. Does not give error as well. Pandas-Python.

huangapple go评论71阅读模式
英文:

Data frame indexing not working as it should be. Does not give error as well. Pandas-Python

问题

我试图将列C中的值设置为np.nan,范围在列C中的值之间。

我试着这样做:

df.loc[(df['C'] < 2) & (df['C'] > 5), 'C'] = np.nan

它不会产生任何错误或警告,但也不会有任何效果,数据框保持不变。

有人知道发生了什么吗?我也尝试了一些不建议的解决方案,但它们也没有起作用:

df['C'][(df['C'] < 2) & (df['C'] > 5)] = np.nan

df['C'].loc[(df['C'] < 2) & (df['C'] > 5)] = np.nan

(注意:上述代码是对您提供的Python代码的翻译,仅返回翻译的部分,不包含其他内容。)

英文:

Lets say we have a dataframe:
'''

df = pd.DataFrame({&#39;A&#39;: &#39;foo bar foo bar foo bar foo foo&#39;.split(),
                   &#39;B&#39;: &#39;one one two three two two one three&#39;.split(),
                   &#39;C&#39;: np.arange(8), &#39;D&#39;: np.arange(8)**2})
df

'''

I am trying to set Values of column C to np.nan for a range of values in column C.

I am trying to set nan values for all values in C that are less than 2 and greater than 5.

I am doing like this:

&#39;&#39;&#39;df.loc[(df[&#39;C&#39;]&lt;2) &amp; (df[&#39;C&#39;]&gt;5),&#39;C&#39;]=np.nan&#39;&#39;&#39;

It does not give any error or warning but also does nothing and the dataframe remains the same.

Does anyone know whats going on? I also tried (not recommended solutions) but they also did not work:

&#39;&#39;&#39; 
df[&#39;C&#39;][(df[&#39;C&#39;]&lt;2) &amp; (df[&#39;C&#39;]&gt;5)]=np.nan

df[&#39;C&#39;].loc[(df[&#39;C&#39;]&lt;2) &amp; (df[&#39;C&#39;]&gt;5)]=np.nan
&#39;&#39;&#39;

答案1

得分: 0

你需要使用 OR 而不是 and,因为 C 包含单个值,请使用:

df.loc[(df['C'] < 2) | (df['C'] > 5), 'C'] = np.nan
英文:

Since C contains a single value , you would need an OR instead of an and, please use:

df.loc[(df[&#39;C&#39;]&lt;2) | (df[&#39;C&#39;]&gt;5),&#39;C&#39;]=np.nan

huangapple
  • 本文由 发表于 2020年1月3日 23:08:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/59580914.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定