如何将for循环生成的字符串添加到带表头的空pandas DataFrame中
报错原因
DataFrame.append()方法仅支持传入Series、DataFrame类型的对象,不能直接拼接字符串类型的变量,所以触发了类型错误。另外需要注意,pandas 2.0及以上版本已经正式移除了append()方法,更推荐使用批量赋值或者pd.concat()实现需求。
推荐解决方案
不需要循环逐行添加,先批量生成所有链接的列表再一次性转为DataFrame,性能远高于逐行添加:
import pandas as pd # 批量生成链接列表 link_list = [f'https://google.com/assets/{i}' for i in range(1,10)] # 直接生成带指定表头的DataFrame linkdf = pd.DataFrame(link_list, columns=['Link'])
运行后即可得到你需要的结果:
Link 0 https://google.com/assets/1 1 https://google.com/assets/2 2 https://google.com/assets/3 ... 8 https://google.com/assets/9
循环逐行添加的实现方案
如果业务场景必须在循环过程中逐行写入,可以选择以下两种兼容方式:
方法1:使用loc按索引赋值
linkdf = pd.DataFrame(columns=['Link']) for i in range(1,10): l = f'https://google.com/assets/{i}' # 取当前DataFrame的长度作为新行的索引进行赋值 linkdf.loc[len(linkdf)] = l
方法2:使用pd.concat拼接
linkdf = pd.DataFrame(columns=['Link']) for i in range(1,10): l = f'https://google.com/assets/{i}' # 将单个字符串转为单行DataFrame后再拼接 row_df = pd.DataFrame([{'Link': l}]) linkdf = pd.concat([linkdf, row_df], ignore_index=True)
内容的提问来源于stack exchange,提问作者Zac
相关产品推荐
相关产品推荐

