Home > OS >  How to save result of for loop in existing input dataframe
How to save result of for loop in existing input dataframe

Time:11-17

My input data frame df is below

external_id

sw_1
sw_2
sw_3
Sw_55

and my output data frame output_df should be

external_id : Status

sw_1 :Hello Sw_1
sw_2 :Hello sw_2
sw_3 :hello sw_3
Sw_55 :Hello sw_55

Till now I have done this. Able to create new df for for loop output only. I want to store for loop result in existing data frame.

df = pd.read_csv(r'/Users/man/Desktop/input.csv')

output_df = df.copy()
output_df['Status'] = ""

list2 = []

for i in df['external_id']:
    x =  "Hello  "   i
    list2.append(x)

df1 = pd.DataFrame(list2)
print(df1)

Actually I have input data frame which contains external_id and I want to call API for each external_id and then store result of api call (status_code and API response) in existing data frame against of each external_id.

CodePudding user response:

It is really still not clear to me what you want to achieve or how you get results of your API, since it just doesn't appear in your code example, but maybe this helps. Your Input is called df. In your code you make a copy and name it output_df but then you never use it. The new created list will be assigned to df1 but you said you want to have a new column in your df. Input:

  external_id
0        sw_1
1        sw_2
2        sw_3
3       Sw_55
result = []
for value in df['external_id']:
    some_value = 'Hello' # here your API should return something for each of your id's
    result.append(some_value   ': '   value) # be aware that `value` and `some_value`need to be strings, maybe convert them first, then append.

df['Status'] = result
print(df)

Output:

  external_id        Status
0        sw_1   Hello: sw_1
1        sw_2   Hello: sw_2
2        sw_3   Hello: sw_3
3       Sw_55  Hello: Sw_55
  • Related