I've a array of data in Pandas and I'm trying to print second character of every string in col1. I can't figure out how to do it. I can easily print the second character of the each string individually, for example:
array.col1[0][1]
However I'd like to print the second character from every row, so there would be a "list" of second characters.
I've tried
array.col1[0:][1]
but that just returns the second line as a whole of col1.
Any advice?
You can use str
to access the string methods for the column/Series and then slice the strings as normal:
>>> df = pd.DataFrame(['foo', 'bar', 'baz'], columns=['col1'])
>>> df
col1
0 foo
1 bar
2 baz
>>> df.col1.str[1]
0 o
1 a
2 a
This str
attribute also gives you access variety of very useful vectorised string methods, many of which are instantly recognisable from Python's own assortment of built-in string methods (split
, replace
, etc.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With