How do you pop multiple columns off a Pandas dataframe, into a new dataframe?

后端 未结 2 529
无人共我
无人共我 2021-02-12 15:13

Suppose I have the following:

df = pd.DataFrame({\'a\':range(2), \'b\':range(2), \'c\':range(2), \'d\':range(2)})

I\'d like to \"pop\" two colu

2条回答
  •  执念已碎
    2021-02-12 15:40

    Here's an alternative, but I'm not sure if it's more classy than your original solution:

    df2 = pd.DataFrame([df.pop(x) for x in ['c', 'd']]).T
    df3 = pd.DataFrame([df.pop(x) for x in ['a', 'b']]).T
    

    Output:

    print(df2)
    #   c  d
    #0  0  0
    #1  1  1
    
    print(df3)
    #   a  b
    #0  0  0
    #1  1  1
    

提交回复
热议问题