将元组添加到 Pandas DataFrame

5

我正在尝试纵向连接一些元组,更好的说法是我正在将这些元组插入数据框中。但是到目前为止还无法做到。问题出现在我试图横向添加它们而不是纵向。

data_frame = pandas.DataFrame(columns=("A","B","C","D"))
str1 = "Doodles are the logo-incorporating works of art that Google regularly features on its homepage. They began in 1998 with a stick figure by Google co-founders Larry Page and Sergey Brin -- to indicate they were attending the Burning Man festival. Since then the doodles have become works of art -- some of them high-tech and complex -- created by a team of doodlers. Stay tuned here for more of this year's doodles"

aa = str1.split()
bb = zip(aa[0:4])

data_frame.append(bb,ignore_index=True,verify_integrity=False) 

我是否需要遍历元组中的每个单词才能使用insert

1个回答

4

你可以这样做

In [8]: index=list('ABCD')

In [9]: df = pd.DataFrame(columns=index)

In [11]: df.append(Series(aa[0:4],index=index),ignore_index=True)
Out[11]: 
         A    B    C                   D
0  Doodles  are  the  logo-incorporating

如果你有很多这样的行要追加,可以创建一个列表,然后在末尾使用DataFame(list_of_series)

In [13]: DataFrame([ aa[0:4], aa[5:8] ],columns=list('ABCD'))
Out[13]: 
         A    B     C                   D
0  Doodles  are   the  logo-incorporating
1       of  art  that                None

哈!@LonelySoul,这也可以用元组来实现;你想要使用元组而不是字符串有什么原因吗? - Jeff
那我就收回先前的话! :) - Andy Hayden
感谢@Jeff。不幸的是,我的列数太多了,所以第二个选项可以工作,但可能需要迭代几次。 - LonelySoul
第二个选项快得多,也是更“推荐”的方式;追加必须保持复制。 - Jeff
这里的“index”名称非常具有误导性。 - Gulzar

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