【问题标题】:Trying to add looped string to empty dataframe pandas尝试将循环字符串添加到空数据框熊猫
【发布时间】:2021-09-21 00:34:06
【问题描述】:

我正在尝试使用 for 循环生成链接并尝试将它们添加到我的空数据框中,如下例所示:

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


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

但我收到如下错误:

TypeError: 无法连接类型为 '' 的对象;只要 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]
  • 您是否真的想使用循环?

标签: python pandas


【解决方案1】:

先创建列表,然后传递给DataFramelike:

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

如果确实需要将数据添加到空DataFrame(速度很慢):

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 - 使用了L.append(l) 而不是linkdf = linkdf.append ?
  • @Zac - print (L) 是什么?是列表吗?
  • 谢谢你 jezrael 你的解决方案有效 :)
【解决方案2】:

或者为什么不只是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 嗯,为什么?
  • 这是我的大代码的一小部分问题,用您的解决方案更改它将不得不更改我的整个代码,再次感谢您。
猜你喜欢
  • 2017-10-12
  • 2017-02-24
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 2013-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多