阻止 pandas 将int转换为float [英] Stop Pandas from converting int to float

查看:122
本文介绍了阻止 pandas 将int转换为float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataFrame.以下是两个相关的列:一个是int的列,而另一个是str的列.

I have a DataFrame. Two relevant columns are the following: one is a column of int and another is a column of str.

我知道,如果我在int列中插入NaN,Pandas会将所有int都转换为float,因为int没有NaN值.

I understand that if I insert NaN into the int column, Pandas will convert all the int into float because there is no NaN value for an int.

但是,当我在str列中插入None时,Pandas也会将我所有的int都转换为float.这对我来说没有意义-为什么我在第2列中输入的值会影响第1列?

However, when I insert None into the str column, Pandas converts all my int to float as well. This doesn't make sense to me - why does the value I put in column 2 affect column 1?

这是一个简单的工作示例(Python 2):

Here's a simple working example (Python 2):

import pandas as pd
df = pd.DataFrame()
df["int"] = pd.Series([], dtype=int)
df["str"] = pd.Series([], dtype=str)
df.loc[0] = [0, "zero"]
print df
print
df.loc[1] = [1, None]
print df

输出为

   int   str
0    0  zero

   int   str
0  0.0  zero
1  1.0   NaN

有什么方法可以使输出如下:

Is there any way to make the output the following:

   int   str
0    0  zero

   int   str
0    0  zero
1    1   NaN

,而无需将第一列重铸到int.

without recasting the first column to int.

  • 我更喜欢使用int而不是float,因为其中的实际数据 该列是整数.如果没有解决方法,我只会 不过请使用float.

  • I prefer using int instead of float because the actual data in that column are integers. If there's not workaround, I'll just use float though.

我希望不必重铸,因为在我的实际代码中,我不是
存储实际的dtype.

I prefer not having to recast because in my actual code, I don't
store the actual dtype.

我还需要逐行插入数据.

I also need the data inserted row-by-row.

推荐答案

如果设置dtype=object,则您的系列将能够包含任意数据类型:

If you set dtype=object, your series will be able to contain arbitrary data types:

df["int"] = pd.Series([], dtype=object)
df["str"] = pd.Series([], dtype=str)
df.loc[0] = [0, "zero"]
print(df)
print()
df.loc[1] = [1, None]
print(df)

   int   str
0    0  zero
1  NaN   NaN

  int   str
0   0  zero
1   1  None

这篇关于阻止 pandas 将int转换为float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆