Is there a pandas function to display the first/last n columns, as in .head() & .tail()?

后端 未结 5 949
花落未央
花落未央 2020-12-05 15:13

I love using the .head() and .tail() functions in pandas to circumstantially display a certain amount of rows (sometimes I want less, sometimes I w

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 15:43

    No, such methods are not supplied by Pandas, but it is easy to make these methods yourself:

    import pandas as pd
    def front(self, n):
        return self.iloc[:, :n]
    
    def back(self, n):
        return self.iloc[:, -n:]
    
    pd.DataFrame.front = front
    pd.DataFrame.back = back
    
    df = pd.DataFrame(np.random.randint(10, size=(4,10)))
    

    So that now all DataFrame would possess these methods:

    In [272]: df.front(4)
    Out[272]: 
       0  1  2  3
    0  2  5  2  8
    1  9  9  1  3
    2  7  0  7  4
    3  8  3  9  2
    
    In [273]: df.back(3)
    Out[273]: 
       7  8  9
    0  3  2  7
    1  9  9  4
    2  5  7  1
    3  3  2  5
    
    In [274]: df.front(4).back(2)
    Out[274]: 
       2  3
    0  2  8
    1  1  3
    2  7  4
    3  9  2
    

    If you put the code in a utility module, say, utils_pandas.py, then you can activate it with an import statement:

    import utils_pandas
    

提交回复
热议问题