You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas将嵌套元组列表转换为指定结构的DataFrame

问题

我有一个嵌套元组列表,想用Pandas生成DataFrame,每个内元组的元素对应一列。但发现移除每个内元组最后两个元素时能得到预期结果,加上这两个元素后,最后两列会被错误填充NaN。

原代码:

# 将现有字典转为DataFrame
final_report_df = pd.DataFrame.from_dict(final_report,orient="index")
# 用chain降低嵌套层级
prepare_data_to_df = list(chain.from_iterable(all_orders))
df_all_orders = pd.DataFrame(prepare_data_to_df, columns=["Id", "Date", "Price", "Label", "Profit/Loss ($)", "Profit/Loss (%)"])
df_all_orders.drop("Id", axis=1, inplace=True)

嵌套元组示例:

((58, '2022-04-28', 85.0199966430664, 'BUY', 8501.99966430664, 100), 
 (67, '2022-05-11', 77.54000091552734, 'STOP BUY', -747.9995727539062, -0.08797925220982794))

期望生成的DataFrame包含7列:Date、Price、Label、Profit/Loss ($)、Profit/Loss (%)、Amount Invested、Stock Shares,要求:

  • Date、Price、Label两行都填充对应值
  • Profit/Loss相关列仅在第二行填充
  • Amount Invested取第一个元组的倒数第二个值,Stock Shares取第一个元组的最后一个值,两行都填充该值

解决方案

核心是针对性拆分嵌套元组、提取字段,而非直接展平结构,以此精准控制每列的填充逻辑。具体实现代码如下:

from itertools import chain
import pandas as pd

# 示例嵌套元组(可替换为实际的all_orders数据)
all_orders = [((58, '2022-04-28', 85.0199966430664, 'BUY', 8501.99966430664, 100), 
               (67, '2022-05-11', 77.54000091552734, 'STOP BUY', -747.9995727539062, -0.08797925220982794))]

# 提取全局复用的投资金额和持股数(从第一个元组的倒数第二、最后一位取值)
first_tuple = all_orders[0][0]
amount_invested = first_tuple[-2]
stock_shares = first_tuple[-1]

# 构造DataFrame的行数据列表
data_rows = []
for order_pair in all_orders:
    for idx, order in enumerate(order_pair):
        # 拆分当前元组的字段
        _, date, price, label, pl_usd, pl_pct = order
        # 利润列仅第二行填充,第一行设为None(Pandas自动转为NaN)
        pl_usd_val = pl_usd if idx == 1 else None
        pl_pct_val = pl_pct if idx == 1 else None
        # 组装行数据
        data_rows.append({
            "Date": date,
            "Price": price,
            "Label": label,
            "Profit/Loss ($)": pl_usd_val,
            "Profit/Loss (%)": pl_pct_val,
            "Amount Invested": amount_invested,
            "Stock Shares": stock_shares
        })

# 生成目标DataFrame
df_all_orders = pd.DataFrame(data_rows)
print(df_all_orders)

运行后输出结果:

Date      Price     Label  Profit/Loss ($)  Profit/Loss (%)  Amount Invested  Stock Shares
0  2022-04-28  85.019997       BUY              NaN               NaN      8501.999664           100
1  2022-05-11  77.540001  STOP BUY      -747.999573         -0.087979      8501.999664           100

关键说明

  • 放弃直接展平嵌套结构的方式,改为逐元组提取字段,避免字段错位导致的NaN填充错误
  • 提前提取全局复用的Amount Invested和Stock Shares,确保所有行统一填充该值
  • 通过元组索引判断是否为第二行,仅在该行填充利润相关列,第一行留空

内容的提问来源于stack exchange,提问作者Márcio Scotuzzi Jr.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 06:45:31