.str.get
This is the easiest way to specify string methods.
# Setup df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]}) df AB 0 xyz 123 1 abc 456 2 foobar 789 df.dtypes A object B int64 dtype: object
For columns of a string (read: object ) type, use
df['C'] = df['A'].str[0]
For non-numeric columns, you must first convert .astype , as shown in @Ed Chum's answer.
df['D'] = df['B'].astype(str).str[0]
df ABCD 0 xyz 123 x 1 1 abc 456 a 4 2 foobar 789 f 7
List comprehension and indexing
A simple list comprehension will work well and will probably be faster.
# For string columns df['C'] = [x[0] for x in df['A']] # For numeric columns df['D'] = [str(x)[0] for x in df['B']]
df ABCD 0 xyz 123 x 1 1 abc 456 a 4 2 foobar 789 f 7
coldspeed
source share