Reputation: 3146
I have a dataframe like this
import pandas as pd
d={'x':[8,5,6,7],
'cord':['(3,0)','(2,0)','(6,0)','(1,0)']}
df=pd.DataFrame.from_dict(d)
I would like to create df['y'] which will have the first 'cord' value and shift to get 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, does not exist, NaN
3 (1,0) 7 2 #Index 1, First value (1,0)
Upvotes: 0
Views: 2396
Reputation: 5362
Make a separate column, which is the 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 look confusing, but it simply splits the string '(a,b)' twice, first on ','
, and then on '('
. Finally, it casts the remaining string ,'a'
, to an integer.
Now use the cord1 column to make the y column
df['y'] = df.cord1[ df.cord1.values].values
being careful to pass the values. Now drop the 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
Upvotes: 2