英文:
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({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': 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:
'''df.loc[(df['C']<2) & (df['C']>5),'C']=np.nan'''
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:
'''
df['C'][(df['C']<2) & (df['C']>5)]=np.nan
df['C'].loc[(df['C']<2) & (df['C']>5)]=np.nan
'''
答案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['C']<2) | (df['C']>5),'C']=np.nan
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论