【问题标题】:How to add an empty row after a definite row in python dataframe?如何在python数据框中的确定行之后添加一个空行?
【发布时间】:2018-08-22 21:06:27
【问题描述】:

我在 python 中处理一个巨大的数据框,有时我需要在数据框的确定位置添加一个空行或几行。对于这个问题,我创建了一个小数据框 df 以显示我想要实现的目标。

>  df = pd.DataFrame(np.random.randint(10, size = (3,3)), columns =
> ['A','B','C'])
>        A  B  C
>     0  4  5  2
>     1  6  7  0
>     2  8  1  9

假设我需要添加一个空行,如果我在“C”列中有一个零值。这里应该在第二行之后添加空行。所以最后我想要一个新的数据框,比如:

>new_df
>        A    B    C
>     0  4    5    2
>     1  6    7    0
>     2  nan  nan  nan
>     3  8    1    9

我尝试使用 concat 和 append,但没有得到我想要的。请问你能帮帮我吗?

【问题讨论】:

    标签: python pandas for-loop dataframe concat


    【解决方案1】:

    你可以这样试试:

    l = df[df['C']==0].index.tolist()
    for c, i in enumerate(l):
        dfs = np.split(df, [i+1+c])
        df = pd.concat([dfs[0], pd.DataFrame([[np.NaN, np.NaN, np.NaN]], columns=df.columns), dfs[1]], ignore_index=True)
    print df
    

    输入:

       A  B  C
    0  4  3  0
    1  4  0  4
    2  4  4  2
    3  3  2  1
    4  3  1  2
    5  4  1  4
    6  1  0  4
    7  0  2  0
    8  2  0  3
    9  4  1  3
    

    输出:

        A    B    C
    0   4.0  3.0  0.0
    1   NaN  NaN  NaN
    2   4.0  0.0  4.0
    3   4.0  4.0  2.0
    4   3.0  2.0  1.0
    5   3.0  1.0  2.0
    6   4.0  1.0  4.0
    7   1.0  0.0  4.0
    8   0.0  2.0  0.0
    9   NaN  NaN  NaN
    10  2.0  0.0  3.0
    11  4.0  1.0  3.0
    

    最后一件事:可能会发生最后一行在“C”中为 0,因此您可以添加:

    if df["C"].iloc[-1] == 0 :
        df.loc[len(df)] = [np.NaN, np.NaN, np.NaN]
    

    【讨论】:

    • 非常感谢。它也适用于我的真实数据框
    【解决方案2】:

    尝试使用切片。

    首先,您需要找到 C == 0 的行。因此,让我们为此创建一个 bool df。我将其命名为“a”:

    a = (df['C'] == 0)
    

    所以,只要 C == 0,a == True。

    现在我们需要找到C == 0的每一行的索引,创建一个空行并将其添加到df中:

    df2 = df.copy() #make a copy because we want to be safe here
    for i in df.loc[a].index:
        empty_row = pd.DataFrame([], index=[i]) #creating the empty data
        j = i + 1 #just to get things easier to read
        df2 = pd.concat([df2.ix[:i], empty_row, df2.ix[j:]]) #slicing the df
    
    df2 = df2.reset_index(drop=True) #reset the index
    

    我必须说...我不知道您的 df 的大小以及是否足够快,但请尝试一下

    【讨论】:

    • 非常感谢您的代码和您的详细解释。它有效!
    【解决方案3】:

    如果您知道要在其中插入新行的索引,concat 可能是一个解决方案。

    示例数据框:

    df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
    #    A  B  C
    # 0  1  4  7
    # 1  2  5  8
    # 2  3  6  9
    

    您的新行作为索引为 1 的数据框:

    new_row = pd.DataFrame({'A': np.nan, 'B': np.nan,'C': np.nan}, index=[1])
    

    在第二行之后插入新行:

    new_df = pd.concat([df.loc[:1], new_row, df.loc[2:]]).reset_index(drop=True)
    #      A    B    C
    # 0  1.0  4.0  7.0
    # 1  2.0  5.0  8.0
    # 2  NaN  NaN  NaN
    # 3  3.0  6.0  9.0
    

    【讨论】:

      【解决方案4】:

      这样的东西应该适合你:

      for key, row in df.iterrows():
          if  row['C'] == 0:
              df.loc[key+1] = pd.Series([np.nan])
      

      【讨论】:

      • 使用 for 循环可能不是一个好的选择,因为有人提到数据很大。
      猜你喜欢
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 2018-01-13
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2020-01-06
      相关资源
      最近更新 更多