尝试将循环字符串添加到空数据帧Pandas。

3
我正在尝试使用for循环生成链接,并尝试像以下示例一样将它们添加到我的空数据框中:
linkdf = pd.DataFrame(columns=['Link'])


for i in range(1,10):
  l = 'https://google.com/assets/' + str(i)
  linkdf = linkdf.append(l)

但是我遇到以下错误:

TypeError: 无法连接类型为“<class 'str'>”的对象;只有Series和DataFrame obj是有效的。

是否有一种方法可以将其添加到已提供标题的空数据框中。
想要以下结果:
        Link
0.  https://google.com/assets/1
1   https://google.com/assets/2
2.  https://google.com/assets/3

感谢任何帮助 谢谢


将您的追加语句替换为:linkdf.loc[len(linkdf)] = [l] - Odhian
你真的有必要使用循环吗? - mozway
2个回答

1

首先创建列表,然后将其传递给 DataFrame,如下所示:

L = ['https://google.com/assets/' + str(i) for i in range(1,10)]
linkdf = pd.DataFrame(L,  columns=['Link'])

您的解决方案:
L = []
for i in range(1,10):
  l = 'https://google.com/assets/' + str(i)
  L.append(l)


print (L)
['https://google.com/assets/1', 'https://google.com/assets/2', 
 'https://google.com/assets/3', 'https://google.com/assets/4',  
 'https://google.com/assets/5', 'https://google.com/assets/6', 
 'https://google.com/assets/7', 'https://google.com/assets/8', 
 'https://google.com/assets/9']

linkdf = pd.DataFrame(L,  columns=['Link'])
print (linkdf)
                          Link
0  https://google.com/assets/1
1  https://google.com/assets/2
2  https://google.com/assets/3
3  https://google.com/assets/4
4  https://google.com/assets/5
5  https://google.com/assets/6
6  https://google.com/assets/7
7  https://google.com/assets/8
8  https://google.com/assets/9

如果真的需要向空数据框中添加数据(这会很慢):

linkdf = pd.DataFrame(columns=['Link'])

for i in range(1,10):
  l = 'https://google.com/assets/' + str(i)
  linkdf = linkdf.append({'Link':l}, ignore_index=True)

嗨,Jezrael,谢谢你回复。我想使用你的第二个解决方案,但出现了这个错误:“TypeError: append()不接受关键字参数”。 - Zac
@Zac - 为什么使用了 L.append(l) 而不是 linkdf = linkdf.append - jezrael
@Zac - “print (L)” 是什么?是列表吗? - jezrael

1
或者为什么不直接使用 np.char.add
linkdf['Link'] = np.char.add('https://google.com/assets/', np.arange(1, 10).astype(str))

>>> linkdf
                          Link
0  https://google.com/assets/1
1  https://google.com/assets/2
2  https://google.com/assets/3
3  https://google.com/assets/4
4  https://google.com/assets/5
5  https://google.com/assets/6
6  https://google.com/assets/7
7  https://google.com/assets/8
8  https://google.com/assets/9
>>> 

抱歉,u12-forward,这可能不是我正在寻找的解决方案,但感谢您花时间。 - Zac
1
@Zac 嗯,为什么? - U13-Forward
这只是我庞大代码的一小部分问题,使用您的解决方案更改它将不得不更改我的整个代码,再次感谢您。 - Zac

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接