【问题标题】:use a list of lookup values to sort dataframe and return a timeseries of row values of other columns使用查找值列表对数据框进行排序并返回其他列的行值的时间序列
【发布时间】:2021-11-22 15:59:48
【问题描述】:

我想使用查找表(字符串列表)来搜索数据框列(名称)并返回其他列的行值的时间序列。查找字符串列表不会与名称列中的字符串完全匹配,但会包含相似的字符串(以?开头)。

lookup=["AB","AC","AX"]

DF = name  year  mean  upper  lower
     AB2    2020   4     7      1
     AB_7   2021   5     9      2
     AC1    2022   3     9      2
     AX     2019   4     9      2

返回:

AB.csv

2020  4  7 1
2021  5  9 2

AC.csv

2022 3  9  3

AX.csv

2019 4 9 2

【问题讨论】:

    标签: python pandas dataframe sorting export-to-csv


    【解决方案1】:

    您可以将 Pandas filterregex 参数与 rf'^{selector}' 一起使用。对于每个循环,此正则表达式将仅保留模式与索引列 (set_index('name')) 中字符串开头的 selector 匹配的行 (axis=0)。

    import pandas as pd
    
    df = pd.read_csv('sample.csv')
    print(df)
    
    lookup=["AB","AC","AX"]
    
    df = df.set_index('name')
    for selector in lookup:
        filtered_df = df.filter(regex=rf'^{selector}', axis=0)
        filtered_df.to_csv(f'{selector}.csv', index=False)
    

    AB.csv

    year,mean,upper,lower
    2020,4,7,1
    2021,5,9,2
    

    AC.csv

    year,mean,upper,lower
    2022,3,9,2
    

    AX.csv

    year,mean,upper,lower
    2019,4,9,2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-16
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 2022-11-12
      • 2010-11-18
      相关资源
      最近更新 更多