Pandas:使用循环向单元格添加值

qmb5sa22  于 2023-03-06  发布在  其他
关注(0)|答案(2)|浏览(188)

我需要使用循环向单元格中添加值。我可以使用下面的脚本实现我所寻求的结果,但是需要使用循环在单元格中添加值。下面是代码脚本。

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

如何使用循环添加list(host,ip)的内容:

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
zf9nrax1

zf9nrax11#

使用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)

产出

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
lqfhib0f

lqfhib0f2#

可以使用loc并循环通过它来添加到单元格

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)

输出:

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

相关问题