nicholas.reichel
nicholas.reichel

Reputation: 2270

Convert dataframe index to string and substring?

Wondering whats the easiest way to split the following dataframes index into substrings and set the second piece as a column in the new dataframe.

Input:
          Ask    Bid   Last Open_Int Vol
245.0P  11.36  11.15  10.41       37  30
225.0C  10.31  10.23   10.3       52   5
224.5C  10.78  10.67     12       72  72
223.5C  11.68  11.56  12.68       89  59
244.5P  10.83  10.64   8.65      118  22
244.0P  10.34  10.15   9.93      137  10

Output:
          Ask    Bid   Last Open_Int Vol Type
245.0P  11.36  11.15  10.41       37  30 P
225.0C  10.31  10.23   10.3       52   5 C
224.5C  10.78  10.67     12       72  72 C
223.5C  11.68  11.56  12.68       89  59 C
244.5P  10.83  10.64   8.65      118  22 P
244.0P  10.34  10.15   9.93      137  10 P

Upvotes: 3

Views: 4200

Answers (3)

Quentin
Quentin

Reputation: 700

If your index is consistent, here's a straightforward approach to this problem df['Type'] = [str(_)[-1] for _ in df.index]

Upvotes: 0

Alexey Trofimov
Alexey Trofimov

Reputation: 5017

For your very example this is the solution:

df['type'] = df.index.str[-1]

Upvotes: 2

piRSquared
piRSquared

Reputation: 294488

df.assign(Type=df.index.str[-1])

          Ask    Bid   Last  Open_Int  Vol Type
245.0P  11.36  11.15  10.41        37   30    P
225.0C  10.31  10.23  10.30        52    5    C
224.5C  10.78  10.67  12.00        72   72    C
223.5C  11.68  11.56  12.68        89   59    C
244.5P  10.83  10.64   8.65       118   22    P
244.0P  10.34  10.15   9.93       137   10    P

Upvotes: 6

Related Questions