【问题标题】:根据列名自动创建多个python数据集
【发布时间】:2022-01-19 17:05:30
【问题描述】:

我有一个庞大的数据集,其中包含以下列:“Eas_1”、“Eas_2”等到“Eas_40”和“Nor_1”到“Nor_40”。我想自动创建多个单独的数据集,其中包含以相同数字结尾的所有列(按列名称编号分组)和作为值粘贴在新列中的列编号 (Bin)。

我的数据框:

df = pd.DataFrame({
"Eas_1": [3, 4, 9, 1],
"Eas_2": [4, 5, 10, 2],
"Nor_1": [9, 7, 9, 2],
"Nor_2": [10, 8, 10, 3],  
"Error_1": [2, 5, 1, 6], 
"Error_2": [5, 0, 3, 2], 
})

我不知道如何创建Bin 列并粘贴列名值,但我可以像这样手动分离数据集:

df1 = df.filter(regex='_1')
df2 = df.filter(regex='_2')

这对我来说需要付出很多努力,而且每次获得新数据时我都必须更改脚本。这就是我想象的最终结果:

df1 = pd.DataFrame({
"Eas_1": [3, 4, 9, 1],
"Nor_1": [9, 7, 9, 2],
"Error_1": [2, 5, 1, 6], 
"Bin": [1, 1, 1, 1], 
})

提前致谢!

【问题讨论】:

    标签: python pandas dataframe group-by


    【解决方案1】:

    您可以使用.str.extract 提取后缀,然后对其进行分组:

    suffixes = df.columns.str.extract('(\d+)$', expand=False)
    
    for label, data in df.groupby(suffixes, axis=1): 
        print('-'*10, label, '-'*10)
        print(data)
    

    注意要收集您的数据帧,您可以:

    dfs = [data for _, data in df.groupby(suffixes, axis=1)]
    
    # access the second dataframe
    dfs[1]
    

    输出:

    ---------- 1 ----------
       Eas_1  Nor_1  Error_1
    0      3      9        2
    1      4      7        5
    2      9      9        1
    3      1      2        6
    ---------- 2 ----------
       Eas_2  Nor_2  Error_2
    0      4     10        5
    1      5      8        0
    2     10     10        3
    3      2      3        2
    

    【讨论】:

    • 看起来很有希望!有没有办法可以将它作为单独的数据框获取?例如 df2(仅由 Eas_2、Nor_2、Error_2 组成)?谢谢!
    • 是的,请参阅更新的答案。
    • 这解决了我的问题中最难的部分......格子!如果我没有得到更好的回复,我会将您的回复标记为答案。
    猜你喜欢
    • 2021-01-31
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 2020-03-20
    • 2018-05-01
    • 2019-03-19
    相关资源
    最近更新 更多