IT Learning

実践形式でITのお勉強

Python

【Python】From DataFrame To list type

投稿日:

Overview

Pandas can get data from a database with read_sql easily.
Here we can show how to convert dataframe to list type for only one row from database.

Example table in databse

a,b,c are columns of this test_table.

abc
110100
220200
330300
440400
test_table

Let’s get only “a” column from this table with pandas.
These are sample code.

import pandas as pd
import psycopg2

connection = psycopg2.connect(host='host', dbname='database', user='username', password='password')
df = pd.read_sql("SELECT a FROM test_table", connection)
df.head()

Result

If you want to convert this result from dataframe to list type, you may think like [1, 2, 3, 4].

There is a simple method to convert dataframe to list, values.tolist().

This is a example to convert with values.tolist().

df.values.tolist()

#Result
[[1], [2], [3], [4]]

You can find the result is a little different from the list type we want.
That is double list but we want single one.

But it is quite normal because the result from sql is dataframe even thought it has just one column.

Solution

To use itertools library, you can get single list type from the dataframe.

This is the example

import itertools
a = df.values.tolist()
list(itertools.chain.from_iterable(a))

#result
[1, 2, 3, 4]

This method is so useful. Please try it.

関連記事

-Python

執筆者:


comment

Your email address will not be published.

Language Switcher

Categories