python - 迭代数据框列:TypeError: 'float' object is not subscriptable
问题描述
我有一个数据框( ),其中df
有一列名为Id
Id
0 3
1 67
2 356
3
:
50 P4
51 P5
52 678
53
54 2
该列有一个类型:dtype: object
我已经计算出最大 Id 值并分配给一个名为 maxId 的变量(它是 678,并且我希望将一个顺序增加的 maxId 应用于空元素,所以在这个例子中我的输出将是:
Id
0 3
1 67
2 356
3 679
:
50 P4
51 P5
52 678
53 680
54 2
其中元素 3 和 53 分别被赋值为 679 和 680。
我尝试了以下代码,我在列中循环查找空元素,然后将 maxId 应用于这些:
for item, frame in df['Id'].iteritems():
if pd.isnull(frame):
maxId = maxId + 1
frame['Id'] = maxId
但我收到一个错误:
TypeError:“浮动”对象不可下标
我需要做什么才能修复?
解决方案
# calculate maximum value
maxId = int(pd.to_numeric(df['Id'], errors='coerce').max())
# calculate Boolean series of nulls
nulls = df['Id'].isnull()
# assign range starting from one above maxId
df.loc[nulls, 'Id'] = np.arange(maxId + 1, maxId + 1 + nulls.sum())
print(df)
# Id
# 0 3
# 1 67
# 2 356
# 3 679
# 50 P4
# 51 P5
# 52 678
# 53 680
# 54 2
推荐阅读
- r - 如何在for循环中选择一列
- asp.net-core - 如何在 asp.net core 中处理标签助手?
- linux - 使用分隔符连接多个 yaml 文件
- react-native - 共享多堆栈导航器的导航选项
- sql - 如何在 Teradata SQL 中合并 Sum 和 Rank 函数?
- dictionary - 如何重新调用 sys.getsizeof(dict) 以便在使用 PyPy 时保留功能?
- batch-file - 是否有相当于 Linux 的“sdiff -s”命令的批处理?
- angular - 从浏览器获取 'blocked:other' 错误状态 - 在 Angular 应用程序中,我进行了 rest api 调用以从服务器获取信息
- sql - 有没有办法用不同的 WHERE 语句两次加入同一个表并创建两个新字段?
- docker - Ansible & Docker:需要建立从 Ansible 容器到 Docker 主机的 ssh 会话