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值在另一个列表中。

相关推荐
qq_214782619 小时前
pandas“将”迎来v3.0.0大版本更新!
python·pandas
数据科学项目实践1 天前
建模步骤 3 :数据探索(EDA) — 1、初步了解数据:常用函数
人工智能·python·机器学习·数据挖掘·数据分析·pandas·数据可视化
光羽隹衡1 天前
Pandas库的基础数据类型
pandas
Pyeako4 天前
python中pandas库的使用(超详细)
开发语言·python·pandas
ranchor6666 天前
excel+pandas使用str.contains() 的典型例子
excel·pandas
啊巴矲6 天前
小白从零开始勇闯人工智能:机器学习初级篇(pandas库)
人工智能·机器学习·pandas
Keep__Fighting6 天前
【机器学习:集成算法】
人工智能·算法·机器学习·pandas·集成学习·sklearn
Hi_kenyon6 天前
Pandas Cheatsheet I
python·pandas
万粉变现经纪人6 天前
如何解决 pip install 网络报错 403 Forbidden(访问被阻止)问题
数据库·python·pycharm·beautifulsoup·bug·pandas·pip