python - 如何在包含 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
等。
知道我必须放什么吗?
解决方案
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
推荐阅读
- kubernetes - 用本地机器中文件的值覆盖 GKE 上部署的 Helm-chart 值?
- macos - Mac 开发者的隐私是否得到保障?
- google-chrome - 铬轮廓仪火焰图表中的大间隙
- arduino - 电线插头激活 Arduino 报警器
- javascript - 如何使以数字开头的电子邮件在 RTL 上而不是 test-mail.com@000 上正确显示?
- unix - gnu并行管道sed - 没有输入文件错误
- azure - 将数据从本地 SQL 服务器复制和整合到 Azure Blob
- powershell - 基于另一个参数的已指定值,制表符完成一个参数值
- pandas - Pandas Dictionary:如何通过将输入值与分配给单个键的多个值匹配来返回键
- javascript - 使用 Ajax 的按钮在 Django 项目中不起作用