Create new column in pandas dataframe as function of another column

My pandas dataframe has an existing "div" column that has a row. I want to create a new column (newcol) whose value is equal to the first line character in the div.

I tried to point out several ways, but it doesn't work.

results['newcol'] = results['div']

gives me a complete string (as expected) not the first char.

results['newcol'] = results['Div'].values[0]

and results['newcol'] = results['Div'][0]

makes newcol on each line equal to the Div on the first line.

results['newcol'] = str(results['Div'])

and results['newcol'] = str(results['Div'])[0]

convert the whole series ['Div'] to one string and return it to newcol.

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

+3


source to share


1 answer


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 conclusion:

  |   A   | B | C 
------------------
0 | hello | 1 | h
------------------
1 | world | 2 | w

      

+7


source







All Articles