0
df  = pd.DataFrame(columns=['w','x','y','z'])

I'm trying to insert a new index row by row, and add values to certain columns. If I were adding one value to a specific column, I could do: df.loc['a','x'] = 2

However what if I'd like to add values to several columns in one go, like this:

{'x':2, 'z':3}

is there a way to do this in pandas?

3 Answers 3

2

reindex and assign

df.reindex(['a']).assign(**d)

     w  x    y  z
a  NaN  2  NaN  3

Where:

d = {'x':2, 'z':3}
Sign up to request clarification or add additional context in comments.

Comments

2
df=pd.DataFrame(d,index=['a']).combine_first(df)
    w  x   y  z
a NaN  2 NaN  3

1 Comment

I don't quite understand what OP wants. HOWEVER I think that is clever.
1

Use loc but selecting multiple columns and assign an iterable (like a list or tuple)

df.loc['a',['x','z']] = [2,3]

Or as suggested from @jfaccioni, in case the data is a dictionary d:

df.loc['a', list(d.keys())] = list(d.values())

2 Comments

OP could also do df.loc['a', list(d.keys())] = list(d.values()) if the dictionary structure is preferred.
Thank you very much, I added the edit to reflect both ways.

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.