如何将MySQL查询结果转换为适配ta-lib的Pandas DataFrame格式
Got it, converting that list of tuples from your MySQL query into the exact Pandas DataFrame structure you need for TA-Lib is straightforward. Here's how to replicate the same format you get from importing a CSV:
Step-by-Step Implementation
First, make sure you have Pandas imported (you're already using it for CSV imports, so this should be covered):
import pandas as pdDefine the column names to match your CSV's structure—this is key to getting the exact same DataFrame layout:
column_names = ['time', 'open', 'high', 'low', 'close']Convert your MySQL result list directly into a DataFrame. Let's say your query results are stored in a variable called
mysql_data:df = pd.DataFrame(mysql_data, columns=column_names)
Quick Check
Run df.head() to confirm the structure matches what you get from pd.read_csv()—you'll see the same column names and row format, ready for TA-Lib analysis.
Optional: Fix Data Types (If Needed)
Depending on your MySQL connector setup, sometimes numeric values might come through as strings. If that's the case, explicitly cast the columns to the correct types:
# Convert price columns to floats df[['open', 'high', 'low', 'close']] = df[['open', 'high', 'low', 'close']].astype(float) # Ensure timestamp is integer type df['time'] = df['time'].astype(int)
This works because Pandas' DataFrame constructor natively handles iterables of tuples as input, and the columns parameter lets you map each position in the tuple to the correct column name—exactly replicating the CSV import result.
内容的提问来源于stack exchange,提问作者Helmuth

