emanuel lemos
emanuel lemos

Reputation: 59

add values in Pandas DataFrame

I want to add values in a dataframe. But i want to write clean code (short and faster). I really want to improve my skill in writing. Suppose that we have a DataFrame and 3 values

df=pd.DataFrame({"Name":[],"ID":[],"LastName":[]})
value1="ema"
value2=023123
value3="Perez"

I can write:

df.append([value1,value2,value3])

but the output is gonna create a new column like

0  | Name | ID | LastName

ema | nan | nan | nan

023123 | nan | nan| nan

Perez | nan | nan | nan

i want the next output with the best clean code

Name | ID | LastName

ema | 023123 | Perez

There are a way to do this , without append one by one? (i want the best short\fast code)

Upvotes: 0

Views: 246

Answers (2)

alluraendless
alluraendless

Reputation: 86

Here the explanation:

First set your 3 values into an array

values=[value1,value2,value3]

and make variable as index marker when lopping latter

i = 0

Then use the code below

for column in df.columns:
    df.loc[0,column] = values[i]
    i+=1

column in df.columns will give you all the name of the column in the DataFrame

and df.loc[0,column] = values[i] will set the values at index i to row=0 and column=column

[Here the code and the result]

1

Upvotes: 1

Epsi95
Epsi95

Reputation: 9047

You can convert the values to dict then use append

df.append(dict(zip(['Name', 'ID', 'LastName'],[value1,value2,value3])), ignore_index=True)
    Name    ID  LastName
0   ema 23123.0 Perez

Upvotes: 2

Related Questions