0

I'm trying to convert a single row DataFrame to a list (without headers) but It's not working as I expect.

import pandas as pd

    df = pd.DataFrame({'Price': [1000],
                       'Area': [520],
                       'Weight': [20]})

    df_list = df.values.tolist()

    print(df_list)
    [[1000, 520, 20]]

However I was expecting the output to be something like: [1000, 520, 20]

Can you help me spotting the error?

3 Answers 3

4

Select first row by position, so output is Series, so output is not nested list:

print (df.iloc[0])
Price     1000
Area       520
Weight      20
Name: 0, dtype: int64

print (type(df.iloc[0]))
<class 'pandas.core.series.Series'>

df_list = df.iloc[0].tolist()
print (df_list)
[1000, 520, 20]
Sign up to request clarification or add additional context in comments.

Comments

2

Try this :

import pandas as pd

df = pd.DataFrame({'Price': [1000],
                       'Area': [520],
                       'Weight': [20]})

df_list = df.values.tolist()[0]

print(df_list) # prints [1000, 520, 20] 

Comments

2

For take the output that you want you should only take the first element. If you controll the type(df_list) you will see that is a list.

df = pd.DataFrame({'Price': [1000],'Area': [520],'Weight': [20]})
df_list = df.values.tolist()
print(df_list[0])

[1000, 520, 20]

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.