首页 > 解决方案 > 如何在包含 Null 值的熊猫中创建数据框

问题描述

我尝试在下面创建故意缺少一些信息的数据框。即,type一条记录应为空。

df = {'id': [1, 2, 3, 4, 5],
      'created_at': ['2020-02-01', '2020-02-02', '2020-02-02', '2020-02-02', '2020-02-03'],
      'type': ['red', NaN, 'blue', 'blue', 'yellow']}

df = pd.DataFrame (df, columns = ['id', 'created_at','type', 'converted_tf'])

当我输入所有值时工作得非常好,但我不断收到错误NaN, Null,Na

知道我必须放什么吗?

标签: pythonpandas

解决方案


np.NaN如果需要缺失值,请使用:

import numpy as np
import pandas as pd

df = {'id': [1, 2, 3, 4, 5],
      'created_at': ['2020-02-01', '2020-02-02', '2020-02-02', '2020-02-02', '2020-02-03'],
      'type': ['red', np.NaN, 'blue', 'blue', 'yellow']}

或者float('NaN')也工作:

df = {'id': [1, 2, 3, 4, 5],
      'created_at': ['2020-02-01', '2020-02-02', '2020-02-02', '2020-02-02', '2020-02-03'],
      'type': ['red', float('NaN'), 'blue', 'blue', 'yellow']}

df = pd.DataFrame (df, columns = ['id', 'created_at','type', 'converted_tf'])
print (df)
   id  created_at    type converted_tf
0   1  2020-02-01     red          NaN
1   2  2020-02-02     NaN          NaN
2   3  2020-02-02    blue          NaN
3   4  2020-02-02    blue          NaN
4   5  2020-02-03  yellow          NaN

或者使用None,它大部分时间的工作方式就像np.NaN在熊猫中处理数据一样:

df = {'id': [1, 2, 3, 4, 5],
      'created_at': ['2020-02-01', '2020-02-02', '2020-02-02', '2020-02-02', '2020-02-03'],
      'type': ['red', None, 'blue', 'blue', 'yellow']}

df = pd.DataFrame (df, columns = ['id', 'created_at','type', 'converted_tf'])
print (df)
   id  created_at    type converted_tf
0   1  2020-02-01     red          NaN
1   2  2020-02-02    None          NaN
2   3  2020-02-02    blue          NaN
3   4  2020-02-02    blue          NaN
4   5  2020-02-03  yellow          NaN

推荐阅读