Reputation: 5169
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
Upvotes: 2
Views: 1173
Reputation: 323326
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
Upvotes: 1
Reputation: 9081
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
Upvotes: 0
Reputation: 38415
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
Upvotes: 3