简体   繁体   中英

How to recover back pandas DataFrame rownames and column names after numpy array transformation

I have the following data frame:

import numpy as np
import pandas as pd

x = [1.1,2.1,0.5]
y = [0.1,3.4,7]
gn = ['foo','bar','qux']
df = pd.DataFrame({'gn':gn, 'x':x, 'y':y})
df

which produces this:

In [148]: df
Out[148]:
    gn    x    y
0  foo  1.1  0.1
1  bar  2.1  3.4
2  qux  0.5  7.0

Then I do some transformation after converting to numpy ndarray:

df.set_index("gn",inplace=True)
npar = df.as_matrix()
npar_new = npar + 1
npar_new

Which produces this:

array([[ 2.1,  1.1],
       [ 3.1,  4.4],
       [ 1.5,  8. ]])

My question is how can I recover the column and row name ( gn ) from df into npar_new . The desired final result is:

   gn    x    y
  foo  2.1  1.1
  bar  3.1  4.4
  qux  1.5  8.0

You can try

df_new = pd.DataFrame(npar_new, index = df.index, columns = df.columns)


    x   y
gn      
foo 2.1 1.1
bar 3.1 4.4
qux 1.5 8.0

By using .loc assign the value

df.loc[:,['x','y']]=ary
df
Out[849]: 
    gn    x    y
0  foo  2.1  1.1
1  bar  3.1  4.4
2  qux  1.5  8.0

more info

ary=np.array([[ 2.1,  1.1],
       [ 3.1,  4.4],
       [ 1.5,  8. ]])

Since you have more column

df.loc[:,list(df.set_index("gn"))]=ary

I am having trouble understanding why you would do the array conversion in the first place. Is that a mandate? If not, here's a pure-play pandas version that would do all operations at one go -

df = df + 1

So, full code will be -

import numpy as np
import pandas as pd

x = [1.1,2.1,0.5]
y = [0.1,3.4,7]
gn = ['foo','bar','qux']
df = pd.DataFrame({'gn':gn, 'x':x, 'y':y})
df = df + 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM