3

My pandas dataframe has an existing column, "div", which has a string. I want to make a new column ('newcol') whose value equals the first character of the string in div.

I've tried to specify this several ways but it doesn't work.

results['newcol'] = results['div'] gives me the full string (as expected) not the first char.

results['newcol'] = results['Div'].values[0] and results['newcol'] = results['Div'][0] makes the newcol in every row equal to the 'Div' string of the first row.

results['newcol'] = str(results['Div']) and results['newcol'] = str(results['Div'])[0] convert the entire ['Div']series into a single string and returns that to newcol.

What's the correct way to specify what I want?

1 Answer 1

7

This should work:

import pandas as pd
data = pd.DataFrame({"A": ["hello", "world"], "B": [1, 2]})
data["C"] = data.A.str[0]
data

This is the output:

  |   A   | B | C 
------------------
0 | hello | 1 | h
------------------
1 | world | 2 | w
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.