0

I have multiple columns that I want to merge together, but I want it driven by a table. So a user can specify let's say fields: 'A', 'B', 'C' and another use can say they want 'A', 'B', 'E', 'Z', etc...

So I want this to be dynamic in a sense. In addition between each row value, I need to insert a \n value to have a new line character.

So in my field description, given the first example, I need the string to be formatted as:

'A: ' + df['A'] + "\n" + 'B: ' + df['B'] + '\n' + 'C: ' + df['C'] + '\n'

When working with string data in python, you can leverage the += operation to append text to an existing string, so I thought I could create a column called description on my Pandas dataframe object and then use the += operation to push everything together.

df['description'] = ""
for f in fields:
    df['description'] += f + ": " + df[f] + '\n'

But this raises a typeerror:

TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'str'

Any ideas on how I can do this?

I am using Pandas 0.16.1

Thanks

8
  • Does df['description'] = df['description'] + ... work? If so, that's what you should use. Commented Dec 5, 2016 at 13:18
  • What is your fields variable in the line for f in fields:? Commented Dec 5, 2016 at 13:22
  • Can you provide a larger example? What comes after the df['description]? Commented Dec 5, 2016 at 13:22
  • For me it works perfect, but use pandas 0.19.1 Commented Dec 5, 2016 at 13:22
  • fields = ['A', 'B', 'C'] Commented Dec 5, 2016 at 13:22

1 Answer 1

1

Use this:

df['description'] += f + ": " + df[f].str.cat(sep=' ') + '\n'
Sign up to request clarification or add additional context in comments.

1 Comment

I don't think that's what the OP wants.

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.