Python 如何在数据框中插入一个新列,其中包含通过迭代生成的数据?

Python 如何在数据框中插入一个新列,其中包含通过迭代生成的数据?,python,pandas,append,iteration,concatenation,Python,Pandas,Append,Iteration,Concatenation,我试图在我的AppleStore apps数据框中的Price列之后插入一个名为Price Label的列,方法是迭代该数据框,并在Price=$0.00的应用中附加一个字符串(“Free”或“Not Free”)。因此,我尝试的代码如下所示 for i, row in df.iterrows(): price = row.Price.replace('$','') if price == '0.0': row.append("Free") else:

我试图在我的AppleStore apps数据框中的
Price
列之后插入一个名为
Price Label
的列,方法是迭代该数据框,并在
Price=$0.00的应用中附加一个字符串(“Free”或“Not Free”)。
因此,我尝试的代码如下所示

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



TypeError回溯(最近一次调用上次)
在里面
第6行追加(“自由”)
7其他:
---->第8行追加(“非自由”)
9
10 df.head()
追加中的~\anaconda3\lib\site packages\pandas\core\series.py(self、to\u追加、忽略\u索引、验证\u完整性)
2580 to_concat=[self,to_append]
2581返回concat(
->2582到_concat,忽略索引=忽略索引,验证完整性=验证完整性
2583         )
2584
concat中的~\anaconda3\lib\site packages\pandas\core\reforme\concat.py(objs、axis、join、忽略索引、键、级别、名称、验证完整性、排序、复制)
279验证完整性=验证完整性,
280拷贝=拷贝,
-->281排序=排序,
282     )
283
~\anaconda3\lib\site packages\pandas\core\reforme\concat.py in\uuuuuu init\uuuu(self、objs、axis、join、键、级别、名称、忽略索引、验证完整性、复制、排序)
355“仅系列和数据帧obj有效”。格式(典型=类型(obj))
356                 )
-->357提升类型错误(msg)
358
359#合并
TypeError:无法连接类型为“”的对象;只有Series和DataFrame OBJ有效
然后

df[“价格标签”]=价格标签

然后


df[“price\u label”]=price\u label

尝试添加一个具有默认值的新列,然后更新行,其中price为0:

df['price_label'] = 'Non-Free' # append a new column
df.loc[df['Price'] == '0.0$', 'price_label'] = 'Free' # set the price_label column, where the Price == 0.0$
代码的第二行按“布尔索引”过滤:

本文通过以下示例对其进行了详细说明:


使用loc()按行和列索引选择:

尝试添加具有默认值的新列,然后更新行,其中价格为0:

df['price_label'] = 'Non-Free' # append a new column
df.loc[df['Price'] == '0.0$', 'price_label'] = 'Free' # set the price_label column, where the Price == 0.0$
代码的第二行按“布尔索引”过滤:

本文通过以下示例对其进行了详细说明:

使用loc()按行和列索引选择:

您可以使用返回元素。然后可以使用方法获取
Price
列的位置。然后,您可以指定列的顺序,以便根据需要重新排列它们

使用以下命令:

可以使用返回元素。然后可以使用方法获取
Price
列的位置。然后,您可以指定列的顺序,以便根据需要重新排列它们

使用以下命令:

import numpy as np

# --> make new column named `Price-Label`
df["Price-Label"] = np.where(df["Price"].eq("$0.0"), "Free", "Non-Free")

#--> get the location of `Price` column
price_col_loc = df.columns.get_loc("Price")

#--> Obtain the resulting dataframe by specifying the order of columns
#--> such that Price-Label column appear after the Price column
result = df[list(df.columns[:price_col_loc + 1]) + [df.columns[-1]] + list(df.columns[price_col_loc + 1:-1])]