【问题标题】:Is there a way to allow NaN values to be writen to CSV from panadas?有没有办法允许将 NaN 值从 pandas 写入 CSV?
【发布时间】:2018-04-16 21:24:46
【问题描述】:

我有以下错误builtins.AssertionError: 12 columns passed, passed data had 6 columns 最后 6 列数据会有所不同,所以我很高兴在数据丢失的区域中有None。但是我似乎找不到一种简单的方法来做到这一点,我很确定必须有一个选项,但我在文档或任何谷歌搜索中都看不到它。

我们将不胜感激。我想重申一下,我知道导致问题的原因,并且我知道列中缺少数据。我想忽略丢失的数据,并且很高兴在输出 csv 中有 None 或 NaN。

【问题讨论】:

  • 你用df.to_csv(file)吗?
  • 是的,我已经在问题中提到了这一点
  • 您能分享一个数据示例吗?
  • stackoverflow.com/questions/36405994/… 这可能会有所帮助!
  • 这是一个例子 ('Person', 'Title', 'AnotherPerson', 'AnotherPerson2', 'AnotherPerson3', 'AnotherPerson4', 'Date', 'Group') AbotherPerson 可以到 6 个左右,但最多只能到 2 个。

标签: python python-3.x pandas


【解决方案1】:

我想你有固定的标题,所以我的解决方案是分别扩展每一行:

import pandas as pd
import numpy as np

columns = ('Person', 'Title', 'AnotherPerson', 'AnotherPerson2', 'AnotherPerson3', 'AnotherPerson4', 'Date', 'Group')
mandatory = len(columns)

data = [[1,2,3], [1, 2], [1, 2, 3, 4]]
data = list(map(lambda x: dict(enumerate(x)), data))

data = [[item.get(i, np.nan) for i in range(mandatory)] for item in data]

df = pd.DataFrame(data=data, columns=columns)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 2015-12-11
    相关资源
    最近更新 更多