简体   繁体   English

可能的错误:熊猫试图用浮点数填充int列

[英]possible bug: pandas trying to fill int column with floats

In this example: 在此示例中:

In [1]: df
Out[1]: 
   a    b
0  1  1.1
1  2  2.2
2  1  3.3
3  2  4.4

In [2]: df['c'] = 0

In [2]: df.c[df.a == 1] = df.b[df.a == 1]

In [3]: df
Out[3]: 
   a    b                    c
0  1  1.1  4607632778762754458
1  2  2.2                    0
2  1  3.3  4614613358185178726
3  2  4.4                    0

It seems like the resulting behavior is confusing. 似乎导致的行为令人困惑。 I know that the problem is that I have initialized 'c' as an int column. 我知道问题是我已经将'c'初始化为int列。 If, instead, I use df['c'] = 0. then everything works fine. 相反,如果我使用df['c'] = 0.那么一切正常。 So I get why my example doesn't work. 所以我明白了为什么我的例子不起作用。 It just seems like there could be a more useful result or at least an error message rather than a seemingly random large number. 似乎可能会有更有用的结果,或者至少是一条错误消息,而不是看似随机的大数字。 Definitely a nice to have, rather than need to have. 绝对是一件好事,而不是需要。

You are chain indexing, see here . 您正在对链进行索引,请参阅此处

Use: 采用:

df.loc[df.a==1,'c'] = df['b']

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

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