【问题标题】:Python Pandas: Split by pattern (across rows) in a specific column of DataFramePython Pandas:在 DataFrame 的特定列中按模式(跨行)拆分
【发布时间】:2020-04-23 12:59:08
【问题描述】:

对编码和 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']

提前感谢您的帮助!

【问题讨论】:

  • 欢迎使用stackoverflow,能否请您尝试关注特定的代码部分,谢谢
  • @PV8 谢谢-重写了更具体的代码部分

标签: python arrays pandas dataframe split


【解决方案1】:

我不知道是否有直接使用 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

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

【讨论】:

  • 我正在使用您的代码,但附加到一个空数据框(如下所示)而不是数据集,因此不必单独复制列。 df_new = pd.DataFrame().reindex_like(df) df_new= df_new.iloc[0:0] 这正是我所坚持的,您的代码运行良好,非常感谢!我完全被困在这上面,我真的很感谢你花在这上面的时间:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
  • 1970-01-01
  • 2015-04-11
相关资源
最近更新 更多