0

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)

0

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

looping + pandas dataframes is not The Best Clean Code
But it very readable, but okay i will edit my statement hehe, thankyou

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.