python - Pandas extract data from column -


i have dataframe this

import pandas pd d={'x':[8,5,6,7],    'cord':['(3,0)','(2,0)','(6,0)','(1,0)']} df=pd.dataframe.from_dict(d) 

i create df['y'] have first 'cord' value , shift index value.

    cord  x  y 0  (3,0)  8  1     #index 3, first value in (1,0) 1  (2,0)  5  6     #index 2, first value in (6,0) 2  (6,0)  6  nan   #index 6, not exist, nan 3  (1,0)  7  2     #index 1, first value (1,0) 

make separate column, first element of cord

df['cord1'] = df.cord.map( lambda x: x.split(',')[0].split('(')[-1]).map(int) df #    cord  x  cord1 #0  (3,0)  8      3 #1  (2,0)  5      2 #2  (6,0)  6      6 #3  (1,0)  7      1 

this might confusing, splits string '(a,b)' twice, first on ',' , , on '('. finally, casts remaining string ,'a' , integer.

now use cord1 column make y column

df['y'] =  df.cord1[ df.cord1.values].values 

being careful pass values. drop cord1 column

df.drop( labels='cord1', axis=1, inplace=true)  #df #    cord  x   y #0  (3,0)  8   1 #1  (2,0)  5   6 #2  (6,0)  6 nan #3  (1,0)  7   2 

Comments

Popular posts from this blog

php - Zend Framework / Skeleton-Application / Composer install issue -

c# - Better 64-bit byte array hash -

python - PyCharm Type error Message -