Pandas : Add value to a cell using loops

Question:

There is a need for me to add values to a cell using loops. I can achieve the result I seek using the script below, however the need is to add values in a cell using loops. Shared below is the code script.

import pandas as pd

host = ['R1','R2','R3','R4','R5']
ip = ['192.168.1.10','192.168.1.20','192.168.1.30','192.168.1.40','192.168.1.50']

data = pd.DataFrame({'Hostname' : host,'IP Address' : ip})

# I can create a data frame this way value this way :
data

    Hostname    IP Address
0   R1  192.168.1.10
1   R2  192.168.1.20
2   R3  192.168.1.30
3   R4  192.168.1.40
4   R5  192.168.1.50

How to add content of list (host, ip) using a loop :

for h,i in zip(host,ip):
    # add script 
    
Seek result as:

    Hostname    IP Address
0   R1  192.168.1.10
1   R2  192.168.1.20
2   R3  192.168.1.30
3   R4  192.168.1.40
4   R5  192.168.1.50
    
Asked By: ver_roh

||

Answers:

You can use loc and loop through it to add to cell

host = ['R1','R2','R3','R4','R5']
ip = ['192.168.1.10','192.168.1.20','192.168.1.30','192.168.1.40','192.168.1.50']

data = pd.DataFrame({'Hostname' : host,'IP Address' : ip})

df = pd.DataFrame(columns=['Hostname', 'IP Address'])

for h,i in zip(host,ip):
    df.loc[len(df)] = [h, i]

data = pd.concat([data, df])

data = data.reset_index(drop=True)

print(data)

output:

  Hostname    IP Address
0       R1  192.168.1.10
1       R2  192.168.1.20
2       R3  192.168.1.30
3       R4  192.168.1.40
4       R5  192.168.1.50
5       R1  192.168.1.10
6       R2  192.168.1.20
7       R3  192.168.1.30
8       R4  192.168.1.40
9       R5  192.168.1.50
Answered By: Abdulmajeed

Using append()

import pandas as pd

host = ['R1','R2','R3','R4','R5']
ip = ['192.168.1.10','192.168.1.20','192.168.1.30','192.168.1.40','192.168.1.50']

df = pd.DataFrame()

for h,i in zip(host,ip):
    df = df.append(pd.DataFrame({'Hostname': [h], 'IP Address': [i]}), ignore_index=True)

print(df)

Output

  Hostname    IP Address
0       R1  192.168.1.10
1       R2  192.168.1.20
2       R3  192.168.1.30
3       R4  192.168.1.40
4       R5  192.168.1.50
Answered By: Brian.Z
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.