pandas 类型错误:无法对具有非 np.nan 值的混合类型进行就地布尔设置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42276396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: Cannot do inplace boolean setting on mixed-types with a non np.nan value
提问by Dinosaurius
I am getting the error TypeError: Cannot do inplace boolean setting on mixed-types with a non np.nan value
when I try to replace numeric values in multiple columns by a specific string value.
TypeError: Cannot do inplace boolean setting on mixed-types with a non np.nan value
当我尝试用特定字符串值替换多列中的数值时出现错误。
df =
TYPE VD_1 VD_2 VD_3
AAA 1234 22122 2345
AAA 1234 2345 22122
This is how I do it:
这就是我的做法:
df[df.isin([22122])] = "English"
or
或者
df[df==22122] = "English"
采纳答案by EdChum
If you stack
the df, then you can compare the entire df against the scalar value, replace and then unstack
:
如果你stack
是 df,那么你可以将整个 df 与标量值进行比较,然后替换unstack
:
In [122]:
stack = df.stack()
stack[ stack == 22122] = 'English'
stack.unstack()
Out[122]:
TYPE VD_1 VD_2 VD_3
0 AAA 1234 English 2345
1 AAA 1234 2345 English
or replace
:
或replace
:
In [125]:
df.replace(22122,'English', inplace=True)
df
Out[125]:
TYPE VD_1 VD_2 VD_3
0 AAA 1234 English 2345
1 AAA 1234 2345 English
回答by DanDy
I realize this is an old question, but I believe this answer will be useful for some, as it will allow for replacing values based on complex conditionals.
我意识到这是一个老问题,但我相信这个答案对某些人有用,因为它允许替换基于复杂条件的值。
In [17]: df = df.where(df!=22122, other="English")
In [18]: df
Out[18]:
TYPE VD_1 VD_2 VD_3
0 AAA 1234 English 2345
1 AAA 1234 2345 English
Note that values where the condition in the where clause is notmet are replaced by values in other
.
注意在where子句中的条件是:值没有满足由值替换other
。