【问题标题】:Move given row to end of DataFrame将给定行移动到 DataFrame 的末尾
【发布时间】:2015-09-05 14:12:30
【问题描述】:

我想从 DataFrame 中获取给定的行,并在同一个 DataFrame 之前添加或附加。

我下面的代码就是这样做的,但我不确定我的做法是否正确,或者是否有更简单、更好、更快的方法?

testdf = df.copy()
#get row 
target_row = testdf.ix[[2],:]
#del row from df
testdf.drop([testdf.index[2]], axis=0, inplace=True)
#concat original row to end or start of df
newdf = pd.concat([testdf, target_row], axis=0)

谢谢

【问题讨论】:

    标签: python pandas dataframe concat


    【解决方案1】:

    我会在shifting 之后直接分配给df,然后使用iloc 来引用您要分配行的位置,而不是concat,您必须调用squeeze 以便您只分配值并丢失原始索引值,否则会引发ValueError

    In [210]:
    df = pd.DataFrame({'a':np.arange(5)})
    df
    
    Out[210]:
       a
    0  0
    1  1
    2  2
    3  3
    4  4
    
    In [206]:
    target_row = df.ix[[2],:]
    target_row
    
    Out[206]:
       a
    2  2
    
    In [211]:
    df = df.shift()
    df.iloc[0] = target_row.squeeze()
    df
    
    Out[211]:
       a
    0  2
    1  0
    2  1
    3  2
    4  3
    

    编辑

    在末尾插入:

    In [255]:
    df = pd.DataFrame({'a':np.arange(5)})
    target_row = df.ix[[2],:]
    df = df.shift(-1)
    df.iloc[-1] = target_row.squeeze()
    df
    
    Out[255]:
       a
    0  1
    1  2
    2  3
    3  4
    4  2
    

    另一个更新

    感谢@AsheKetchum 指出我之前的回答是不正确的,现在看到 3 年后我意识到你可以reindex orig df:

    如果我们将索引的副本作为list

    In[24]:
    idx = df.index.tolist()
    idx
    
    Out[24]: [0, 1, 2, 3, 4]
    

    那么我们可以从这个列表中pop 感兴趣的索引:

    In[25]:
    idx.pop(2)
    idx
    
    Out[25]: [0, 1, 3, 4]
    

    现在我们可以 reindex 将其添加到此列表之前:

    In[26]:
    df.reindex([2] + idx)
    
    Out[26]: 
       a
    2  2
    0  0
    1  1
    3  3
    4  4
    

    或附加:

    In[27]:    
    df.reindex(idx+[2])
    
    Out[27]: 
       a
    0  0
    1  1
    3  3
    4  4
    2  2
    

    【讨论】:

    • 这样对吗??在编辑之前的示例中,您使 4 从列 a 中消失。这是想要的输出吗??
    • @AsheKetchum 好点,再看这个问题,OP 做了什么我的回答不正确,我会更新
    • 请注意,.ix 已弃用。请改用.iloc
    【解决方案2】:

    为了提高性能,您可能需要考虑保留要移动到 DataFrame 末尾的所有行的运行列表,然后在单个 pd.concat 操作中一次将它们全部移动。

    df = pd.DataFrame(np.random.rand(5, 3), columns=list('ABC'))
    target_rows = [1, 3, 4]
    
    a = df.iloc[[i for i in df.index if i not in target_rows], :]
    b = df.iloc[target_rows, :]
    >>> pd.concat([a, b])
              A         B         C
    0  0.818722  0.174153  0.522383
    2  0.581577  0.840306  0.985089
    1  0.645752  0.238476  0.670922
    3  0.198271  0.501911  0.954477
    4  0.965488  0.735559  0.701077
    

    【讨论】:

      【解决方案3】:

      我可以将其简化为单行:

      pd.concat([df.ix[0:1], df.ix[3:], df.ix[[2]]])
      

      不过,我看不出您的代码和我的代码有任何性能差异。想必抄袭才是最大的罪魁祸首。

      【讨论】:

        【解决方案4】:

        类似于 YH Wu 写的,如果您知道索引(或索引),您可以在一行中完成。但是,不推荐使用 ix,因此请改用 loc:

        import pandas as pd
        import numpy as np
        
        df = pd.DataFrame({'a':np.arange(5)})
        
        #    a
        # 0  0
        # 1  1
        # 2  2
        # 3  3
        # 4  4
        
        # move the line with index 2 to the end:
        df2 = df.drop(2).append(df.loc[2])
        
        #    a
        # 0  0
        # 1  1
        # 3  3
        # 4  4
        # 2  2
        
        # several indices, moves 3 and 2 to the end in that order:
        to_move = [3, 2]
        df2 = df.drop(to_move).append(df.loc[to_move])
        
        #    a
        # 0  0
        # 1  1
        # 4  4
        # 3  3
        # 2  2
        

        .drop 删除带有您作为参数提供的索引(或索引)的行。使用 df.loc[x] 您可以选择具有索引(或索引)x 的行。如果您编写 df = df.drop... ,则直接将更改应用于原始 DataFrame。如果要重置索引,可以执行“.reset_index(drop=True)”(如果您不想将原始索引保留为新列,则 drop=True)。

        【讨论】:

          【解决方案5】:

          我只是删除一行并在最后追加。

          df = pd.DataFrame({'a':np.arange(5)})
          df.drop(2).append(df.ix[2]).reset_index(drop=True) # move 3rd row
          df.drop(df.head(2).index).append(df.head(2)).reset_index() # move first 2 rows
          

          【讨论】:

          • 您可能需要添加一点评论来解释您的答案。
          猜你喜欢
          • 1970-01-01
          • 2011-12-17
          • 1970-01-01
          • 2018-02-08
          • 2021-10-25
          • 2012-01-12
          • 1970-01-01
          • 1970-01-01
          • 2021-11-21
          相关资源
          最近更新 更多