简体   繁体   中英

How to add new row in csv using Python panda

Hello this is my csv data

        Age      Name
0       22  George
1       33  lucas
2       22  Nick
3       12  Leo
4       32 Adriano
5       53  Bram
6       11  David
7       32  Andrei
8       22 Sergio

i want to use if else statement , for example if George is adult create new row and insert + i mean

Age      Name       Adul
22       George    +

What is best way?

This is my code Which i am using to read data from csv

import pandas as pd
produtos = pd.read_csv('User.csv', nrows=9)
print(produtos)
for i, produto in produtos.iterrows():
    print(i,produto['Age'],produto['Name'])

IIUC, you want to create a new column (not row) call "Adul". You can do this with numpy.where :

import numpy as np

produtos["Adul"] = np.where(produtos["Age"].ge(18), "+", np.nan)
Edit:

To only do this for a specific name, you could use:

name = input("Name")

if name in produtos["Name"].tolist():
    if produtos.loc[produtos["Name"]==name, "Age"] >= 18:
        produtos.loc[produtos["Name"]==name, "Adul"] = "+"

你可以这样做:

produtos["Adul"] = np.where(produtos["Age"] >= 18, "+", np.nan)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM