ian_chan
ian_chan

Reputation: 355

pandas unstack a dataframe and stack series

I have a dataframe and I want to do some operations for some rows

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

For example, I want to take out row 5, 8, 10:

series_5 = df.iloc[5,:]
series_8 = df.iloc[8,:]
series_10 = df.iloc[10,:]

Each of them would be a series indexed by columns of df. its name would be the index of df, e.g.:

>>> series_5
A    22
B    14
C     3
D    22
Name: 5, dtype: int64

After some operation on each of these three series, I want to convert them back to a dataframe that in the same format (and index) as df, i.e.

df_new:

     A   B   C   D
5    56  72  73  92
8    16  13  42  69
10   85  16  68  76

I am now stuck at creating this new dataframe after updating values of series 5, 8, 10 (for demonstration, you can assume the values are the same as before). And I also want to ask about how to do the next step: updating df with df_new for those three rows. Thanks!

Upvotes: 0

Views: 194

Answers (1)

Kyle
Kyle

Reputation: 3318

To create a dataframe from a collection of series:

df_new = pd.DataFrame([series_5, series_8, series_10])

Upvotes: 3

Related Questions