df数据 按列 提取为单个列表

方法1:直接提取为单个列表

复制代码
import pandas as pd

# 单行DataFrame示例
df = pd.DataFrame({
    'a_1': [1],
    'b_1': [10],
    'a_2': [2],
    'b_2': [20],
    'a_3': [3],
    'b_3': [30]
})

# 筛选列名
a_cols = [col for col in df.columns if col.startswith('a_')]
b_cols = [col for col in df.columns if col.startswith('b_')]

# 提取第一行
a_list = df[a_cols].iloc[0].tolist()  # 使用 iloc[0] 获取第一行
b_list = df[b_cols].iloc[0].tolist()

print("a值列表:", a_list)  # [1, 2, 3]
print("b值列表:", b_list)  # [10, 20, 30]

方法2:使用squeeze()方法

复制代码
# squeeze()将单行/单列DataFrame转换为Series
a_series = df.filter(regex='^a_').squeeze()  # 筛选a列并压缩
b_series = df.filter(regex='^b_').squeeze()  # 筛选b列并压缩

a_list = a_series.tolist()
b_list = b_series.tolist()

print("a值列表:", a_list)  # [1, 2, 3]
print("b值列表:", b_list)  # [10, 20, 30]

方法3:使用values0

复制代码
# 直接获取第一行的值
a_values = df.filter(regex='^a_').values[0]  # array([1, 2, 3])
b_values = df.filter(regex='^b_').values[0]  # array([10, 20, 30])

a_list = a_values.tolist()
b_list = b_values.tolist()

print("a值列表:", a_list)
print("b值列表:", b_list)

方法4:处理可能的多行情况(通用方法)

复制代码
def extract_ab_lists(df):
    """通用函数,处理单行或多行DataFrame"""
    a_cols = sorted([col for col in df.columns if col.startswith('a_')], 
                    key=lambda x: int(x.split('_')[1]))
    b_cols = sorted([col for col in df.columns if col.startswith('b_')], 
                    key=lambda x: int(x.split('_')[1]))
    
    if len(df) == 1:
        # 单行情况
        a_list = df[a_cols].iloc[0].tolist()
        b_list = df[b_cols].iloc[0].tolist()
        return a_list, b_list
    else:
        # 多行情况
        a_list = df[a_cols].values.tolist()
        b_list = df[b_cols].values.tolist()
        return a_list, b_list

# 使用示例
a_list, b_list = extract_ab_lists(df)
print("a值列表:", a_list)
print("b值列表:", b_list)

方法5:按数字排序的完整示例

复制代码
# 确保列按数字顺序排序
import re

# 提取并按数字排序
def sort_columns(columns):
    """按a_1, a_2, a_3这样的数字顺序排序"""
    return sorted(columns, key=lambda x: int(re.search(r'\d+', x).group()))

a_cols = sort_columns([col for col in df.columns if col.startswith('a_')])
b_cols = sort_columns([col for col in df.columns if col.startswith('b_')])

# 提取单行数据
row = df.iloc[0]
a_list = [row[col] for col in a_cols]
b_list = [row[col] for col in b_cols]

print("排序后的a值列表:", a_list)  # [1, 2, 3]
print("排序后的b值列表:", b_list)  # [10, 20, 30]

方法6:转换为字典格式

复制代码
# 如果需要更结构化的结果
result = {
    'a_values': df.filter(regex='^a_').squeeze().tolist(),
    'b_values': df.filter(regex='^b_').squeeze().tolist()
}

print("字典格式:", result)
# 输出: {'a_values': [1, 2, 3], 'b_values': [10, 20, 30]}

推荐使用的方法

对于单行DataFrame,最简洁的方法是:

复制代码
# 简洁版
df_single_row = pd.DataFrame({
    'a_1': [1], 'b_1': [10], 'a_2': [2], 'b_2': [20], 'a_3': [3], 'b_3': [30]
})

# 一行代码搞定
a_list = df_single_row.filter(regex='^a_').squeeze().tolist()
b_list = df_single_row.filter(regex='^b_').squeeze().tolist()

print("a:", a_list)  # [1, 2, 3]
print("b:", b_list)  # [10, 20, 30]

关键点:

  1. filter(regex='^a_'):筛选所有以'a_'开头的列

  2. squeeze():将单行DataFrame转换为Series

  3. tolist():将Series转换为列表

这样就能得到你想要的:所有a值在一个列表中,所有b值在另一个列表中。

相关推荐
2601_967979125 天前
一文详解:7个 Pandas stack() 和 unstack() 使用技巧
pandas·数据预处理·dataframe·stack()·unstack()
2601_967979127 天前
pandas重塑层次化索引(stack()和unstack()函数解析)
pandas·重塑·层次化索引·stack()·unstack()
郝学胜-神的一滴8 天前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
弈栈录8 天前
时间序列分析:按日、周、月进行趋势统计
数据分析·pandas
linweidong11 天前
RTX 4090 Ubuntu + ComfyUI + comfy-kitchen 0.2.41 完整部署文档
机器学习·云原生·conda·pandas·scikit-learn
benchmark_cc12 天前
个人开发者接入五档盘口:用 QuantDash 读取单只股票的验收清单与易错点
python·数据分析·pandas·量化交易·股票数据·quantdash
benchmark_cc16 天前
用 QuantDash 读取单只股票五档盘口:抽样、缺失值检查与复现记录
python·数据分析·pandas·量化交易·股票数据·quantdash
benchmark_cc19 天前
单只股票五档盘口接入个人研究仓库:QuantDash 读取、校验与易错点
python·数据分析·pandas·量化交易·股票数据·quantdash
benchmark_cc20 天前
用 QuantDash 读取美股行情:AAPL.US 的运行前检查、排错顺序与数据校验清单
python·数据分析·pandas·量化交易·股票数据·quantdash
databook22 天前
经常听到的透视表是干什么的?
python·数据分析·pandas