1

I've a dataframe column with an string of numbers and I want to convert it into a list of numbers. The output must be a list, since I need be able to pull the index value (for instance, df.probabilities[0][0] and return 0.001).

This my current dataframe:

 probabilities
 0.001, 0.002, 0.003, 0.004

I need this:

  probabilities
  [0.001, 0.002, 0.003, 0.004]

Thank you in advance.

3 Answers 3

1

You can call str.split and float using a list comprehension in DataFrame.apply:


import pandas as pd


def parse_probabilities(string):
    return [float(value) for value in string.split(',')]


df = pd.DataFrame({'probabilities': ['0.001, 0.002, 0.003, 0.004']})

df['probabilities'] = df['probabilities'].apply(parse_probabilities)

print(df)
print(df.probabilities[0][0])

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

Comments

0

Uses .str accessor with split:

df['probabilities'].str.split(',\s?')

2 Comments

That will give you a list of strings, not a list of numbers
Good observation.. let me fix that!
0
df = pd.DataFrame({'probabilities': ['0.001, 0.002, 0.003, 0.004', '0.005, 0.006, 0.007, 0.008']})
df.probabilities = df.probabilities.str.split(',', expand=True).astype(float).apply(list, axis=1)
print(df, df.probabilities[0][0], sep='\n')
                  probabilities
0  [0.001, 0.002, 0.003, 0.004]
1  [0.005, 0.006, 0.007, 0.008]
0.001

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.