【问题标题】:Convert sparse pandas dataframe with `NaN` into integer values [duplicate]将带有`NaN`的稀疏熊猫数据帧转换为整数值[重复]
【发布时间】:2017-01-02 06:08:07
【问题描述】:

我有一个二进制熊猫数据框,其值为 0.01.0NaN

import pandas as pd
df = pd.read_csv("file.csv")

我想将浮点数 1.00.0 转换为整数 10。不幸的是,由于NaN 值,此命令失败:

df.applymap(int)

错误是:

ValueError: ('cannot convert float NaN to integer', 'occurred at index 0')

是否有“熊猫”替代品?

【问题讨论】:

  • 您希望NaN 的整数值是多少? 0.0, 1.0, NaN 的输入输出应该是什么?
  • @recursive 我希望 1.0 成为 10.0 成为 0NaN 被忽略

标签: python pandas binary int


【解决方案1】:

更新:

如果您需要好看的 字符串 值,您可以这样做:

In [84]: df.astype(object)
Out[84]:
   a  b    c
0  0  1    0
1  0  0    1
2  1  1    1
3  0  1    1
4  1  1  NaN

但所有值 - 都是字符串(object 在熊猫术语中):

In [85]: df.astype(object).dtypes
Out[85]:
a    object
b    object
c    object
dtype: object

针对 500K 行 DF 的计时:

In [86]: df = pd.concat([df] * 10**5, ignore_index=True)

In [87]: df.shape
Out[87]: (500000, 3)

In [88]: %timeit df.astype(object)
10 loops, best of 3: 113 ms per loop

In [89]: %timeit df.applymap(lambda x: int(x) if pd.notnull(x) else x).astype(object)
1 loop, best of 3: 7.86 s per loop

旧答案:

AFAIK 你不能使用现代熊猫版本来做到这一点。

这是一个演示:

In [52]: df
Out[52]:
     a    b    c
0  1.0  NaN  0.0
1  NaN  1.0  1.0
2  0.0  0.0  NaN

In [53]: df[pd.isnull(df)] = -1

In [54]: df
Out[54]:
     a    b    c
0  1.0 -1.0  0.0
1 -1.0  1.0  1.0
2  0.0  0.0 -1.0

In [55]: df = df.astype(int)

In [56]: df
Out[56]:
   a  b  c
0  1 -1  0
1 -1  1  1
2  0  0 -1

我们快到了,让我们将-1 替换为NaN

In [57]: df[df < 0] = np.nan

In [58]: df
Out[58]:
     a    b    c
0  1.0  NaN  0.0
1  NaN  1.0  1.0
2  0.0  0.0  NaN

另一个演示:

In [60]: df = pd.DataFrame(np.random.choice([0,1], (5,3)), columns=list('abc'))

In [61]: df
Out[61]:
   a  b  c
0  1  0  0
1  1  0  1
2  0  1  1
3  0  0  1
4  0  0  1

如果我们将其中的单个单元格更改为NaN,看看c 列会发生什么:

In [62]: df.loc[4, 'c'] = np.nan

In [63]: df
Out[63]:
   a  b    c
0  1  0  0.0
1  1  0  1.0
2  0  1  1.0
3  0  0  1.0
4  0  0  NaN

【讨论】:

  • 最佳答案似乎是df.astype(object)
  • @ShanZhengYang,所以你不需要integer values作为你的主题?你需要看起来像整数的字符串吗?
  • 实际上,这也不起作用......每当我通过df.to_cvs()保存矩阵时,它会将整数保存为浮点数......还有其他想法该怎么做?
【解决方案2】:

从 pandas 0.24(2019 年 1 月)开始,您无需解析为 object,而是使用 nullable integers 来实现所需的功能。使用@MaxU 的例子:

In [125]: df
Out[125]:
   a  b    c
0  0  1  0.0
1  0  0  1.0
2  1  1  1.0
3  0  1  1.0
4  1  1  NaN

In [126]: df.astype('Int64')
Out[126]:
   a  b    c
0  0  1    0
1  0  0    1
2  1  1    1
3  0  1    1
4  1  1  NaN

【讨论】:

    猜你喜欢
    • 2020-09-04
    • 2021-12-14
    • 2018-04-28
    • 2016-08-26
    • 2016-09-09
    • 2012-11-02
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    相关资源
    最近更新 更多