Home > OS >  how to create new columns and insert the values one by one in python and pandas
how to create new columns and insert the values one by one in python and pandas

Time:08-26

this is what my table looks like for example

| Name | post code | 
| :---:| :-------: |
| james| DA4 5FH   |
| Jack | DA5 5FH   |
| john | DA6 5FH   |

1)i am running a for loop so for each item i want to populate on the excel/csv file by creating new columns and add values to the first row so it looks like this

| Name | post code | DOB. |  sport    |
| :---:| :-------: | :---:| :-------: |
| james| DA4 5FH   |1/1/20| football  |
| Jack | DA5 5FH   |
| john | DA6 5FH   |
  1. of course in the second item from the loop i don't want to create the header again because the header DOB and sport already exist
| Name | post code | DOB. |  sport    |
| :---:| :-------: | :---:| :-------: |
| james| DA4 5FH   |1/1/20| football  |
| Jack | DA5 5FH   |1/1/97| basketball|
| john | DA6 5FH   |

how can i use panda to insert value to the next row. the first time it will include the headers but the second item will not need to insert the headers

CodePudding user response:

To run a loop and insert line by line, you can do :

Your way to loop with i:

    new_sport_value = your request result
    
    rowIndex = df.index[i]
    df.loc[rowIndex, 'sports'] = new_sport_value

Pandas is not made to work like that so maybe consider working with other objects and then convert it to dataframes

CodePudding user response:

Maybe something like this:

API = ["1A", "2B", "3C"] # Here is your APIs

for i in range(len(API)):
    try:
        df.loc[i, "API"] = API[i]
    except:
        print(f"The API {i}, didn't response")
  • Related