【问题标题】:How to Insert New Rows (with a condition) in Excel using Python / Pandas如何使用 Python / Pandas 在 Excel 中插入新行(有条件)
【发布时间】:2019-08-14 14:13:21
【问题描述】:

当特定列具有特定条件时,我正在尝试使用 pandas 数据框将新行插入到 excel 中

例如:

Input

    A   B   C   D   E
0   AA  111 2   2   
1   CC  222 8   12  
2   DD  333 3   3

Output
    A   B   C   D   E (Output Column)
0   AA  111 2   2   111-2   
1   CC  222 8   8   222-8
2   CC  222 9   9   222-9   
3   CC  222 10  10  222-10
4   CC  222 11  11  222-11
5   CC  222 12  12  222-12
6   DD  333 3   3   333-3

如果您在此处看到 C 列和 D 列,第 1 行的范围为 8-12。所以我需要相应地拆分行。如果 C 和 D 相同,则不追加新行。

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    另一种解决方案,使用Index.repeat 创建输出帧,然后将groupby.cumcountstr 串联更新列CDE 的值:

    df1 = df.loc[df.index.repeat((df.D - df.C).add(1))]
    df1['C'] = df1['C'] + df1.groupby('A').cumcount()
    df1['D'] = df1['C']
    df1['E'] = df['B'].astype(str) + '-' + df1['C'].astype(str)
    

    [出]

        A    B   C   D       E
    0  AA  111   2   2   111-2
    1  CC  222   8   8   222-8
    1  CC  222   9   9   222-9
    1  CC  222  10  10  222-10
    1  CC  222  11  11  222-11
    1  CC  222  12  12  222-12
    2  DD  333   3   3   333-3
    

    【讨论】:

      【解决方案2】:

      我的示例用于从 C 列和 D 列具有不同值的行中获取数据,并为它们创建新数据。接下来将这个新数据添加到没有差异的数据中。

      import pandas as pd
      
      # setup data
      data_raw = [['AA', 111, 2, 2], ['CC', 222, 8, 12], ['DD', 333, 3, 3]]
      data = pd.DataFrame(data_raw, columns=['A', 'B', 'C','D'])
      
      # get items with no difference
      rest_of_data = data.loc[data['C'] == data['D']]
      
      # create value for E column
      rest_of_data = rest_of_data.copy()
      rest_of_data['E'] = str(str(rest_of_data['B'].values[0]) + '-' + str(rest_of_data['C'].values[0]))
      
      # find items with difference
      difference_data = data.loc[data['C'] != data['D']]
      
      # get numbers of elements to create
      start = int(difference_data['C'])
      stop = int(difference_data['D'])
      
      # create new data
      create_data = []
      for i in range(start,stop+1,1):
          new = [difference_data['A'].values[0], difference_data['B'].values[0], i, i, str(difference_data['B'].values[0])+'-'+str(i)]
          create_data.append(new)
      
      new_data = pd.DataFrame(create_data, columns=['A', 'B', 'C','D', 'E'])
      
      # concatenate frames
      frames = [rest_of_data, new_data]
      result = pd.concat(frames, ignore_index=True)
      

      结果:

          A    B   C   D       E
      0  AA  111   2   2   111-2
      1  DD  333   3   3   111-2
      2  CC  222   8   8   222-8
      3  CC  222   9   9   222-9
      4  CC  222  10  10  222-10
      5  CC  222  11  11  222-11
      6  CC  222  12  12  222-12
      

      【讨论】:

        【解决方案3】:
        df = pd.DataFrame(
            data={
                'A': ['AA', 'CC', 'DD'],
                'B': [111, 222, 333],
                'C':[2, 8, 3],
                'D':[2, 12, 3],
                'E':[None, None, None],
            }
        )
        
        new_df = pd.DataFrame(
            data={
                'A': [],
                'B': [],
                'C': [],
                'D': [],
                'E': [],
            },
            dtype=np.int64
        )
        
        for idx, row in df.iterrows():
            if row['C'] == row['D']:
                new_df = new_df.append(
                    pd.DataFrame(
                        data={
                            'A': [row['A']],
                            'B': [int(row['B'])],
                            'C': [int(row['C'])],
                            'D': [int(row['D'])],
                            'E': [str(row['B']) + '-' + str(row['D'])],
                        }
                    )
                )
            elif int(row['D']) > int(row['C']):
                tmp_c = int(row['C'])
                tmp_d = int(row['D'])
                while tmp_d >= tmp_c: 
                    new_df = new_df.append(
                        pd.DataFrame(
                            data={
                                'A': [row['A']],
                                'B': [int(row['B'])],
                                'C': [int(row['C'])],
                                'D': [tmp_c],
                                'E': [str(row['B']) + '-' + str(tmp_c)],
                            }
                        )
                    )
                    tmp_c += 1
        
        print(new_df)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-24
          • 2015-04-13
          • 2016-04-27
          • 1970-01-01
          • 2014-12-22
          • 1970-01-01
          • 1970-01-01
          • 2022-12-10
          相关资源
          最近更新 更多