How to append rows in a pandas dataframe in a for loop?

前端 未结 5 1558
日久生厌
日久生厌 2020-11-29 16:43

I have the following for loop:

for i in links:
     data = urllib2.urlopen(str(i)).read()
     data = json.loads(data)
     data = pd.DataFrame(data.items())         


        
5条回答
  •  粉色の甜心
    2020-11-29 17:17

    First, create a empty DataFrame with column names, after that, inside the for loop, you must define a dictionary (a row) with the data to append:

    df = pd.DataFrame(columns=['A'])
    for i in range(5):
        df = df.append({'A': i}, ignore_index=True)
    df
       A
    0  0
    1  1
    2  2
    3  3
    4  4
    

    If you want to add a row with more columns, the code will looks like this:

    df = pd.DataFrame(columns=['A','B','C'])
    for i in range(5):
        df = df.append({'A': i,
                        'B': i * 2,
                        'C': i * 3,
                       }
                       ,ignore_index=True
                      )
    df
        A   B   C
    0   0   0   0
    1   1   2   3
    2   2   4   6
    3   3   6   9
    4   4   8   12
    

    Source

提交回复
热议问题