Tarique
Tarique

Reputation: 1461

Diagonal Dataframe to 1 row

I need to convert a diagonal Dataframe to 1 row Dataframe. Input:

df = pd.DataFrame([[7, 0, 0, 0],
                   [0, 2, 0, 0],
                   [0, 0, 3, 0],
                   [0, 0, 0, 8],],
                  columns=list('ABCD'))
   A  B  C  D
0  7  0  0  0
1  0  2  0  0
2  0  0  3  0
3  0  0  0  8

Expected output:

   A  B  C  D
0  7  2  3  8

what i tried so far to do this:

df1 = df.sum().to_frame().transpose()
df1
   A  B  C  D
0  7  2  3  8

It does the job. But is there any elegant way to do this by groupby or some other pandas builtin?

Upvotes: 0

Views: 383

Answers (2)

David Erickson
David Erickson

Reputation: 16683

You can use: np.diagonal(df):

pd.DataFrame(np.diagonal(df), df.columns).T

    A   B   C   D
0   7   2   3   8

Upvotes: 1

sammywemmy
sammywemmy

Reputation: 28644

Not sure if there is any other 'elegant' way, I can only propose alternatives:

Use numpy.diagonal

pd.DataFrame([df.to_numpy().diagonal()], columns=df.columns)

    A   B   C   D
0   7   2   3   8

Use groupby with boolean (not sure if this is better than your solution):

df.groupby([True] * len(df), as_index=False).sum()


    A   B   C   D
0   7   2   3   8

Upvotes: 1

Related Questions