我有一个巨大的数据集,列有:"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],
})提前感谢!
发布于 2021-12-16 15:49:14
您可以使用.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)要收集您的数据文件,请执行Note:
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 2https://stackoverflow.com/questions/70381867
复制相似问题