Andre
Andre

Reputation: 694

Python: DataFrame to List conversion

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?

Upvotes: 0

Views: 379

Answers (3)

jezrael
jezrael

Reputation: 862511

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]

Upvotes: 4

Krzysztof Witkowski
Krzysztof Witkowski

Reputation: 155

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]

Upvotes: 2

AmirHmZ
AmirHmZ

Reputation: 556

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] 

Upvotes: 2

Related Questions