Python:在数据帧的特定列中按模式(跨行)拆分

2024-04-29 10:15:29 发布

您现在位置:Python中文网/ 问答频道 /正文

非常新的编码和python,所以请容忍我。我看了又看,但没有找到解决这个问题的办法

我有一个来自大型excel电子表格的数据框,其中“示踪气体类型”列(随机行)中有一个连续的“1”、“2”、“1”、“2”模式。。。新兴的这些行需要从电子表格的其余部分拆分。数据帧的一个示例部分:

   df = {'col1': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'col2': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
                  'Tracer gas type': ['1', '2', '1', '1', '0', '1', '2', '1', '2' ]}
        df = pd.DataFrame(data=df)

图案始终以1开始,可能重复未知次数,并以2结束。在本例中,如果正确拆分,新df应仅包含旧df的前2行和最后4行:

作为起点,我已经能够拆分值为“1”的数据帧,但无法拆分“1”、“2”、“1”、“2”。。。使用此方法的部分:

        self.new_df = self.df[self.df['Tracer gas type'] == '1']

提前感谢您的帮助


Tags: 数据self示例类型编码dftype模式
1条回答
网友
1楼 · 发布于 2024-04-29 10:15:29

我不知道是否有一种简单的方法可以直接使用pandas,但您可以通过基本python在数据帧的所有行上进行迭代,如下所示:

# create a new empty dataset
df_new_data = {
    'col1': []
    , 'col2': []
    , 'Tracer gas type': []
}

last_tgt = ''
this_tgt = ''
# go over all rows in df.values
for row_id in range(0, len(df.values)):
    this_tgt = df.iloc[row_id][2]
    # leave out the first row for comparison
    if(last_tgt != ''): 
        # if the last tgt was 1 and this is 2 then write both rows to the new dataset
        if(this_tgt == '2' and last_tgt == '1'): 
            # print(str(row_id-1) + ' - ' + str(row_id)) # just for debugging
            df_new_data['col1'].append(df.iloc[row_id-1][0])
            df_new_data['col2'].append(df.iloc[row_id-1][1])
            df_new_data['Tracer gas type'].append(df.iloc[row_id-1][2])
            df_new_data['col1'].append(df.iloc[row_id][0])
            df_new_data['col2'].append(df.iloc[row_id][1])
            df_new_data['Tracer gas type'].append(df.iloc[row_id][2])
    # remember this value as 'last value'
    last_tgt = this_tgt

# create new DataFrame from dataset
df_new = pd.DataFrame(df_new_data)
df_new

这可能不是最漂亮的方式,但它会产生你作为例子给出的期望结果

相关问题 更多 >