Avij
Avij

Reputation: 694

Dynamically reshape the dataframe in pandas

I am having a dataframe which has 4 columns and 4 rows. I need to reshape it into 2 columns and 4 rows. The 2 new columns are result of addition of values of col1 + col3 and col2 +col4. I do not wish to create any other memory object for it.

I am trying

df['A','B'] = df['A']+df['C'],df['B']+df['D']

Can it be achieved by using drop function only? Is there any other simpler method for this?

Upvotes: 1

Views: 882

Answers (3)

user2285236
user2285236

Reputation:

The dynamic way of summing two columns at a time is to use groupby:

df.groupby(np.arange(len(df.columns)) % 2, axis=1).sum()
Out[11]: 
    0   1
0   2   4
1  10  12
2  18  20
3  26  28

You can use rename afterwards if you want to change column names but that would require a logic.

Upvotes: 3

piRSquared
piRSquared

Reputation: 294508

Consider the sample dataframe df

df = pd.DataFrame(np.arange(16).reshape(4, 4), columns=list('ABCD'))
df

    A   B   C   D
0   0   1   2   3
1   4   5   6   7
2   8   9  10  11
3  12  13  14  15

One line of code

pd.DataFrame(
    df.values.reshape(4, 2, 2).transpose(0, 2, 1).sum(2),
    columns=df.columns[:2]
)

    A   B
0   2   4
1  10  12
2  18  20
3  26  28

Another line of code

df.iloc[:, :2] + df.iloc[:, 2:4].values

    A   B
0   2   4
1  10  12
2  18  20
3  26  28

Yet another

df.assign(A=df.A + df.C, B=df.B + df.D).drop(['C', 'D'], 1)

    A   B
0   2   4
1  10  12
2  18  20
3  26  28

Upvotes: 0

jxstanford
jxstanford

Reputation: 3387

This works for me:

df['A'], df['B'] = df['A'] + df['C'], df['B'] + df['D']
df.drop(['C','D'], axis=1)

Upvotes: 0

Related Questions