首页 > 解决方案 > 迭代数据框列: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:“浮动”对象不可下标

我需要做什么才能修复?

标签: pythonpandas

解决方案


使用pd.Series.isnullnp.arange

# 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

推荐阅读