3

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
2
  • How would you split exactly? I mean how would you split 245.0P? Commented Apr 13, 2017 at 18:41
  • [245.0, P]. I dont know, substring, with the lengths of the string as the inputs to substring? And then df['Type'] = substring_out[1]. I can figure it out by iterating over the df, but theres the fancy lambda map stuff that can do this all in one line. Wondering if anyone can show me that trick again. Commented Apr 13, 2017 at 18:43

3 Answers 3

6
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

Sign up to request clarification or add additional context in comments.

4 Comments

You are so fast!
I get error. Probably because my dataframe is a json doc thats read from disk and making some encoding issue? AttributeError: Can only use .str accessor with string values (i.e. inferred_type is 'string', 'unicode' or 'mixed')
@mobone use df.assign(Type=df.index.astype(str).str[-1])
Was my mistake. I had df and option_df, used the wrong dataframe. Thanks!
2

For your very example this is the solution:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.