【问题标题】:How to insert a row in DataFrame in pandas? (Python)如何在熊猫的DataFrame中插入一行? (Python)
【发布时间】:2018-02-12 10:58:30
【问题描述】:

假设我有以下数据框:

a=np.array([[10,20,30,40],[5,20,35,50],[0,5,10,15]])
b=pd.DataFrame(a, columns=["n1", "n2", "n3", "n4"])

我对其进行以下计算(第一行和第二行之间的差异):

c=b.diff(1,0)
c.loc[[1]]

然后我想将这一行差异(由c.loc[[1]] 给出)插入我的数据框b。我怎么做?当我尝试时,我得到一个错误ValueError: cannot set a row with mismatched columns"

【问题讨论】:

    标签: python pandas dataframe row


    【解决方案1】:

    使用Series 选择的setting with enlargement loc 和一个[]

    b.loc[len(b)] = b.diff().loc[1]
    print (b)
         n1    n2    n3    n4
    0  10.0  20.0  30.0  40.0
    1   5.0  20.0  35.0  50.0
    2   0.0   5.0  10.0  15.0
    3  -5.0   0.0   5.0  10.0
    

    或者使用concatDataFrame[[]]

    c = pd.concat([b, b.diff().loc[[1]]], ignore_index=True)
    print (c)
    
         n1    n2    n3    n4
    0  10.0  20.0  30.0  40.0
    1   5.0  20.0  35.0  50.0
    2   0.0   5.0  10.0  15.0
    3  -5.0   0.0   5.0  10.0
    

    【讨论】:

      【解决方案2】:

      试试

      c = b.diff(axis=0).iloc[1]
      

      c = b.diff(axis=0).loc[1]
      

      输出:

      print(c)
          n1    -5.0
          n2     0.0
          n3     5.0
          n4    10.0
          Name: 1, dtype: float64
      

      将 c 添加到 b 使用 append

      b = b.append(c)
      

      print(b) 的输出

           n1    n2    n3    n4
      0  10.0  20.0  30.0  40.0
      1   5.0  20.0  35.0  50.0
      2   0.0   5.0  10.0  15.0
      1  -5.0   0.0   5.0  10.0
      

      【讨论】:

        猜你喜欢
        • 2020-07-02
        • 2020-08-31
        • 1970-01-01
        • 2021-10-06
        • 1970-01-01
        • 2020-09-25
        • 1970-01-01
        • 2019-01-01
        相关资源
        最近更新 更多