python - 如何在 Dataframe 中插入一个新列,其中包含通过迭代产生的数据?
问题描述
我正在尝试通过遍历数据框并将字符串(“免费”或“非免费”)附加到应用程序中,在我的 AppleStore 应用程序数据框中Price Label
的列之后插入一个名为的列,因此我尝试的代码如下Price
price = $0.00.
for i, row in df.iterrows():
price = row.Price.replace('$','')
if price == '0.0':
row.append("Free")
else:
row.append("Non-Free")
df[column].append("price_label") # in an attempt to add a header to column.
但是后来我遇到了下面的错误消息。谁能告诉我熊猫是否有一种特殊的方式可以将字符串连接到数据框系列/列?与往常一样,我感谢社区的帮助。你们是最棒的。
TypeError Traceback (most recent call last)
<ipython-input-191-c6a90a84d57b> in <module>
6 row.append("Free")
7 else:
----> 8 row.append("Non-Free")
9
10 df.head()
~\anaconda3\lib\site-packages\pandas\core\series.py in append(self, to_append, ignore_index, verify_integrity)
2580 to_concat = [self, to_append]
2581 return concat(
-> 2582 to_concat, ignore_index=ignore_index, verify_integrity=verify_integrity
2583 )
2584
~\anaconda3\lib\site-packages\pandas\core\reshape\concat.py in concat(objs, axis, join, ignore_index, keys, levels, names, verify_integrity, sort, copy)
279 verify_integrity=verify_integrity,
280 copy=copy,
--> 281 sort=sort,
282 )
283
~\anaconda3\lib\site-packages\pandas\core\reshape\concat.py in __init__(self, objs, axis, join, keys, levels, names, ignore_index, verify_integrity, copy, sort)
355 "only Series and DataFrame objs are valid".format(typ=type(obj))
356 )
--> 357 raise TypeError(msg)
358
359 # consolidate
TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid
解决方案
price_label = []
for i, row in df.iterrows():
price = row.Price.replace('$','')
if price == '0.0':
price_label.append("Free")
else:
price_label.append("Non-Free")
接着
df["price_label"] = price_label
推荐阅读
- opencv - 如何从相机坐标系获取电视屏幕上的真实世界投影坐标
- c# - 为 Backgroundjob 记录通用接口
- c++ - 以跨平台方式将图像源路径从 C++ 发送到 QML
- docker - Cron 作业杀死所有悬挂的 docker 容器
- view - 我可以在 h2 SCRPT 命令中影响转储/导出顺序吗
- c# - 使用 EF Core 从 PostgreSQL 中查询字节值的长度
- swift - 我如何使用@designable 在情节提要上看到这个设计
- c# - Polly RetryAsync 不工作且代码未记录
- mysql - 子查询中的 mysql sql_mode=only_full_group_by 不起作用
- c# - 导出到excel中的日期格式问题