Get first letter of a string from column

前端 未结 2 817
我寻月下人不归
我寻月下人不归 2020-11-29 02:15

I\'m fighting with pandas and for now I\'m loosing. I have source table similar to this:

import pandas as pd

a=pd.Series([123,22,32,453,45,453,56])
b=pd.Ser         


        
2条回答
  •  执念已碎
    2020-11-29 03:04

    Cast the dtype of the col to str and you can perform vectorised slicing calling str:

    In [29]:
    df['new_col'] = df['First'].astype(str).str[0]
    df
    
    Out[29]:
       First  Second new_col
    0    123     234       1
    1     22    4353       2
    2     32     355       3
    3    453     453       4
    4     45     345       4
    5    453     453       4
    6     56      56       5
    

    if you need to you can cast the dtype back again calling astype(int) on the column

提交回复
热议问题