0

I want to append data from column and a default phrase at the same time into a Pandas DataFrame, db has many columns, not only id_sin & extra...

I tried this:

import pandas as pd
db = pd.DataFrame({'id_sin':['s123','s124','s125','s126'],
                   'extra':['abc','def','ghi','jkl'],
                   ...
})
df = pd.DataFrame(columns=['id_sin','phrase'])
df = df.append([db['id_sin'],['default phrase']*len(db)])

This is the expected result:

>>> df
  id_sin          phrase
0   s123  default phrase
1   s124  default phrase
2   s125  default phrase
3   s126  default phrase

But I am getting an error, please help... thanks in advance!

8
  • 1
    Why not just db['Phrase'] = 'default phrase' ???? Commented Apr 15, 2019 at 17:27
  • I need to take the column and append it with the default phrase... please help! Commented Apr 15, 2019 at 17:29
  • what first part? what errors? Commented Apr 15, 2019 at 17:29
  • My suggestion gives you exactly the output you need Commented Apr 15, 2019 at 17:30
  • 2
    Just to clarify, You have a DataFrame (db) with many columns and what you would like is to create another DataFrame with a subset of the original columns (in this case just 'id_sin') and another column called phrase which takes on a static value for all rows? If so, you want: df = db[['id_sin']].assign(phrase='default phrase'). Otherwise please try to explain the problem more clearly. Commented Apr 15, 2019 at 17:40

1 Answer 1

1

You can create a copy of existing DataFrame and then add new column to it.

import pandas as pd
db = pd.DataFrame({'id_sin':['s123','s124','s125','s126'],
               'extra':['abc','def','ghi','jkl'],
               ...
})

df = pd.DataFrame()
df['id_sin'] = db[['id_sin']]
df['Phrase'] = 'Default Phrase'
Sign up to request clarification or add additional context in comments.

Comments

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.