首页 > 解决方案 > 如何在 Dataframe 中插入一个新列,其中包含通过迭代产生的数据?

问题描述

我正在尝试通过遍历数据框并将字符串(“免费”或“非免费”)附加到应用程序中,在我的 AppleStore 应用程序数据框中Price Label的列之后插入一个名为的列,因此我尝试的代码如下Priceprice = $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


标签: pythonpandasappenditerationconcatenation

解决方案


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


推荐阅读