在python / pandas中附加到系列不起作用

时间:2016-12-20 04:15:48

标签: python pandas dataframe series

我正在尝试将值附加到通过查找第n个和第n个+ 1个元素之间的差异而获得的pandas系列:

Alabama,3,"Shelby, RichardRichard Shelby",Republican,None,"U.S. House,Alabama Senate","University of Alabama, Tuscaloosa(BA;LLB)Birmingham School of Law(JD)","January 3, 1987","(1934-05-06)May 6, 1934(age 82)",2022
Alabama,2,"Sessions, JeffJeff Sessions",Republican,Lawyer in private practice,"Alabama Attorney General,U.S. Attorneyfor theSouthern District of Alabama","Huntingdon College(BA)University of Alabama, Tuscaloosa(JD)","January 3, 1997","(1946-12-24)December 24, 1946(age 69)",2020
Alaska,3,"Murkowski, LisaLisa Murkowski",Republican,Lawyer in private practice,Alaska House,Georgetown University(BA)Willamette University(JD),"December 20, 2002","(1957-05-22)May 22, 1957(age 59)",2022
Alaska,2,"Sullivan, DanDan Sullivan",Republican,Lawyer in private practice,"Alaska Natural Resources Commissioner,Alaska Attorney General,U.S. Assistant Secretary of State for Economic and Business Affairs",Harvard University(BA)Georgetown University(MS;JD),"January 3, 2015","(1964-11-13)November 13, 1964(age 52)",2020
Arizona,3,"McCain, JohnJohn McCain",Republican,None,"U.S. House,U.S. NavyCaptain",United States Naval Academy(BS),"January 3, 1987","(1936-08-29)August 29, 1936(age 80)",2022
Arizona,1,"Flake, JeffJeff Flake",Republican,Nonprofit director,U.S. House,"Brigham Young University, Utah(BA;MA)","January 3, 2013","(1962-12-31)December 31, 1962(age 53)",2018
Arkansas,3,"Boozman, JohnJohn Boozman",Republican,Optometrist,"Rogers Public School Board,U.S. House","University of Arkansas, Fayetteville(attended)Southern College of Optometry(OD)","January 3, 2011","(1950-12-10)December 10, 1950(age 66)",2022

我得到的输出是:

q = pd.Series([])

while i < len(other array):
    diff = some int value
    a = pd.Series([diff], ignore_index=True)
    q.append(a)
    i+=1

为什么我没有得到包含所有附加值的数组?

-

P.S。这是一个数据科学问题,我必须通过搜索数据框找到最多县的州。我正在使用索引值,其中一个状态结束,下一个状态开始(我用来查找差异的数组中的值)以确定处于该状态的县数量。如果有人知道如何比我上面更好地解决这个问题,请告诉我!

2 个答案:

答案 0 :(得分:34)

append方法无法就地工作。相反,它返回一个新的Series对象。所以它应该是:

q = q.append(a)

希望它有所帮助!

答案 1 :(得分:1)

Series.append文档指出,append另一行到该帧的末尾,返回一个新对象。

这些示例似乎有点混乱,因为它似乎可以正常工作,但是如果您仔细观察,您会发现它们使用的是交互式python,它打印上次调用(新对象)的结果,而不是显示原始对象。

调用append的结果实际上是全新的Series

在您的示例中,您每次需要将q分配给.append返回的新对象:

q = pd.Series([])
while i < len(other array):
    diff = some int value
    a = pd.Series([diff], ignore_index=True)
    # change of code here
    q = q.append(a)
    i+=1