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:使用values[0]

复制代码
# 直接获取第一行的值
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值在另一个列表中。

相关推荐
Cloud_Shy61820 小时前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(第十二章 用户定义函数 上篇)
python·数据分析·excel·pandas
星越华夏1 天前
pandas日期类型差值timedelta大于等于7天
pandas
Omics Pro3 天前
填补蛋白质组深度学习预处理教学空白
人工智能·python·深度学习·plotly·numpy·pandas·scikit-learn
星越华夏3 天前
Pandas获取excel表sheet名称
excel·pandas
星越华夏4 天前
PPTX判断包含图表id
python·pandas
Cloud_Shy6184 天前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(第十一章 Python 包跟踪器 上篇)
python·数据分析·excel·pandas·matplotlib
小郑加油5 天前
python学习Day14:实际应用——pandas的筛选与保存
python·学习·pandas
Cloud_Shy6185 天前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(第十章 Python 驱动的 Excel 工具 上篇)
vscode·python·数据分析·excel·pandas
Cloud_Shy6185 天前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(第十章 Python 驱动的 Excel 工具 下篇)
笔记·python·学习·数据分析·excel·pandas
川冰ICE6 天前
Python爬虫实战⑳|Pandas时间序列,趋势分析一网打尽
爬虫·python·pandas