In [1]:
import pandas as pd
In [2]:
df = pd.DataFrame({'a': ['abcde', 'fghij', 'klmno'],
'b': [123, 456, 789]})
In [3]:
print(df)
In [4]:
print(df.dtypes)
In [5]:
print(df['a'].str[:2])
In [6]:
print(df['a'].str[-2:])
In [7]:
print(df['a'].str[::2])
In [8]:
print(df['a'].str[2])
In [9]:
print(df['a'].str[0])
In [10]:
print(df['a'].str[-1])
In [11]:
df['a_head'] = df['a'].str[:2]
print(df)
In [12]:
# print(df['b'].str[:2])
# AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas
In [13]:
print(df['b'].astype(str).str[:2])
In [14]:
print(df['b'].astype(str).str[:2].astype(int))
In [15]:
print((df['b'] / 10).astype(int))