本文介绍了Python PyTd teradata查询到Pandas DataFrame中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PyTd teradata模块从Teradata查询数据,并希望将其读入Pandas DataFrame

I'm using the PyTd teradata module to query data from Teradata and want to read it into a Pandas DataFrame

import teradata
import pandas as pd

# teradata connection
udaExec = teradata.UdaExec(appName="Example", version="1.0",
                           logConsole=False)
session = udaExec.connect(method="odbc", system="", username="", password="")

# Create empty dataframe with column names
query = session.execute("SELECT TOP 1 * FROM table")
cols = [str(d[0]) for d in query.description]
df = pd.DataFrame(columns=cols)

# Read data into dataframe
for row in session.execute("SELECT * FROM table"):
    print type(row)
    df.append(row)

row属于teradata.util.Row class,不能附加到数据框.我尝试将其转换为列表,但格式混乱.

row is of teradata.util.Row class and can't be appended to the dataframe. I tried converting it to a list but the format gets messed up.

如何使用teradata模块将数据从Teradata读取到数据帧中?我无法为此使用pyodbc模块.

How can I read my data into a dataframe from Teradata using the teradata module? I'm not able to use the pyodbc module for this.

是否有更好的方法来创建与数据库中的列名称匹配的空数据框?

Is there a better way to create the empty dataframe with column names matching those in the database?

推荐答案

您可以使用pandas.read_sql:)

You can use pandas.read_sql :)

import teradata
import pandas as pd

# teradata connection
udaExec = teradata.UdaExec(appName="Example", version="1.0",
                           logConsole=False)
with udaExec.connect(method="odbc", system="", username="", password="") as session:


    query ="SELECT * FROM table"

    df = pd.read_sql(query,session)

使用"with"将确保查询后会话结束.希望对您有所帮助:)

Using ‘with’ will ensure close of session after the query. I hope that helped :)

这篇关于Python PyTd teradata查询到Pandas DataFrame中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 09:23