我试图通过在列标题中搜索字符串,从更大的数据帧构建一个子集数据帧。在
df=pd.read_csv('data.csv')
cdf = df.drop(['DateTime'], axis=1)
wells = ['N1','N2','N3','N4','N5','N6','N7','N8','N9']
for well in wells:
wellname = well
well = pd.DataFrame()
well_cols = [col for col in cdf.columns if wellname in col]
well = cdf[well_cols]
我试图在cdf数据帧列中搜索wellname,并将包含该wellname的列放入名为wellname的新数据帧中。在
我可以构建新的子数据帧,但是数据帧的大小为空(0,0),而cdf是(21973,91)。在
well\u cols也可以作为列表正确填充。在
这是一些cdf列标题。每列有20k行数据。在
^{pr2}$我想创建一个包含“well”的每个标题的新数据帧,即所有列的新数据帧,以及列名包含N1的数据,另一个包含N2等
新的数据帧在循环内部正确填充,但在循环中断时消失。。。print(well)
的一段代码输出:
[27884 rows x 10 columns]
N9_Inj_Casing_Gas_Valve ... N9_Inj_Casing_Gas_Pressure
0 74.375000 ... 2485.602364
1 74.520833 ... 2485.346000
2 74.437500 ... 2485.341091
IIUC这就足够了:
如果你想填充一些东西,字典通常是一种方法。在本例中,如果您输入
well_dict['N1']
,您将得到第一个数据帧,依此类推。在迭代数组时,数组的元素不是可变的。也就是说,基于您的示例,它正在做什么:
但是在任何时候您都没有更改数组,也没有为此存储新的数据帧(尽管在迭代结束时,您仍将最后一个数据帧存储在
well
中)。在在我看来,将数据帧存储在dict中更容易使用:
^{pr2}$但是,如果您真的希望它出现在列表中,您可以执行以下操作:
解决这个问题的一种方法是使用}。在
pd.MultiIndex
和{您可以添加一个由井标识符和变量名组成的多重索引。如果您有
df
:您可以使用})。在
^{pr2}$df.columns.str.split('_', expand=True)
来解析好标识符对应的变量名(即a
或{返回:
然后您可以转置数据帧和
groupby
多索引级别0。在要返回未转换的子数据帧列表,可以使用:
其中
wells[0]
是:而
wells[1]
是:最后一步是相当不必要的,因为可以从分组对象
grouped
访问数据。在总而言之:
相关问题 更多 >
编程相关推荐