Reputation: 3619
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?
Upvotes: 3
Views: 1379
Reputation: 31399
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
Upvotes: 7