gpt4 book ai didi

python - 迭代数据框列: TypeError: 'float' object is not subscriptable

转载 作者:行者123 更新时间:2023-11-30 22:01:09 24 4
gpt4 key购买 nike

我有一个数据框 (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。

我尝试了以下代码,我在列中循环查找 null 元素,然后将 maxId 应用于这些元素:

for item, frame in df['Id'].iteritems():
if pd.isnull(frame):
maxId = maxId + 1
frame['Id'] = maxId

但是我收到一个错误:

TypeError: 'float' object is not subscriptable

我需要做什么才能修复?

最佳答案

使用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

关于python - 迭代数据框列: TypeError: 'float' object is not subscriptable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54126037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com