3

Sample Data:

import pandas as pd

df1=pd.DataFrame({'Original City': {'Daimler': 'Chicago',
  'Mitsubishi': 'LA',
  'Tesla': 'Vienna',
  'Toyota': 'Zurich',
  'Renault': 'Sydney',
  'Ford': 'Toronto'}})

df2=pd.DataFrame({'Current City': {'Tesla': 'Amsterdam',
  'Renault': 'Paris',
  'BMW': 'Munich',
  'Fiat': 'Detroit',
  'Audi': 'Berlin',
  'Ferrari': 'Bruxelles'}})

Now my question is:

I am trying to create a column containing whitespace using assign() method:

df1.assign(Original City=df2['Current City'])
                   ^
               #white space

I tried:

df1.assign('Original City'=df2['Current City'])
df1.assign(r'Original City'=df2['Current City'])

And as expected It is giving me an error:

  File "<ipython-input-132-2ac564ac9d47>", line 1
    df1.assign(Original City=df2['Current City'])
                        ^
SyntaxError: invalid syntax

But I can able to assign my column like this:

df1.assign(OriginalCity=df2['Current City'])

Is it possible to create a column containing ' ' space(white space) using assign() method?

3
  • 1
    Having spaces in identifiers are not allowed. dict(a=1) works but dict(a b=1) doesnot Commented Apr 20, 2021 at 14:30
  • @anky Thanks for the information....I also thinked this but I was wondering that Is there a way for doing so :) Commented Apr 20, 2021 at 14:34
  • Does this answer your question? pandas assign with new column name as string Commented Apr 30, 2024 at 12:27

1 Answer 1

6

You can use unpack dictionary:

d = {'Original City':df2['Current City']}
df1.assign(**d)

Or unpack a dataframe:

df1.assign(**df2[['Current City']].rename({'Current City': 'Original City'}))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Quang Hoang....I was thinking to ask this question from many past days

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.