0

Hi I am trying to append rows in a new created pandas dataframe


###expression
for i in active_brain_regions:
    indices = np.where(LM == i)
    expr = gene[indices]
    mean = np.mean(expr)
    dat= [[i, mean, str("nifti")]]
    dd = pd.DataFrame(dat, columns = ['region', 'mean expr', 'gene_id'])
    dd.append(dd)

dd should look like

 0.0  -0.424069   nifti
 1.0       -1.0   nifti
 .
 . 
 .
 11.0    0.23352   nifti

But after running the for loop dd is just a dataframe of size (1,3) with the last entry of region 11..

1 Answer 1

4

You can assign back, because is used pandas method DataFrame.append:

dd = dd.append(dd)

Or create list of DataFrames by pure python append (working inplace) and use concat only once:

L = []
for i in active_brain_regions:
    indices = np.where(LM == i)
    expr = gene[indices]
    mean = np.mean(expr)
    dat= [[i, mean, str("nifti")]]
    dd = pd.DataFrame(dat, columns = ['region', 'mean expr', 'gene_id'])
    L.append(dd)

 df = pd.concat(L, ignore_index=True)

But fastest solution should be create list of lists and pass to DataFrame constructor only once:

L = []
for i in active_brain_regions:
    indices = np.where(LM == i)
    expr = gene[indices]
    mean = np.mean(expr)
    dat= [[i, mean, str("nifti")]]
    L.append(dat)

 df = pd.DataFrame(L, columns = ['region', 'mean expr', 'gene_id'])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.