I have a pretty simple problem that i can't get around.
I create a dataframe and i would like to generate a new column with a sliced string from one column with a slice value from another column.
Ex: From this:
dftest = pd.DataFrame({'string' : ['EXAMPLE']*5, 'position' : [1, 2, 3, 4, 5]})
position string
0 1 EXAMPLE
1 2 EXAMPLE
2 3 EXAMPLE
3 4 EXAMPLE
4 5 EXAMPLE
5 1 OTHER
6 2 OTHER
7 3 OTHER
I want this:
position string new
0 1 EXAMPLE E
1 2 EXAMPLE EX
2 3 EXAMPLE EXA
3 4 EXAMPLE EXAM
4 5 EXAMPLE EXAMP
5 1 OTHER O
6 2 OTHER OT
7 3 OTHER OTH
I tried:
dftest['new'] = dftest.string.str[:dftest.position]
dftest['new'] = dftest.string.str[:dftest['position']]
dftest['new'] = dftest.string[:dftest.position]
as well as different row iteration methods but each time I end up with Nan values.
Any help would be greatly appreciated
You can do the following
dftest['new'] = [dftest.iloc[i]['string'][0:dftest.iloc[i]['position']] for i in range(0,len(dftest))]
This will check the position.
One method is to enumerate the string using a list comprehension.
dftest['new'] = [s[:n] for s, n in zip(dftest.string, dftest.position)]
>>> dftest
position string new
0 1 EXAMPLE E
1 2 EXAMPLE EX
2 3 EXAMPLE EXA
3 4 EXAMPLE EXAM
4 5 EXAMPLE EXAMP
5 1 OTHER O
6 2 OTHER OT
7 3 OTHER OTH
You could use iterrows
method:
for i, row in df.iterrows():
df.loc[i, 'new'] = row['string'][:row['position']]
Example:
In [60]: dftest
Out[60]:
position string
0 1 EXAMPLE
1 2 EXAMPLE
2 3 EXAMPLE
3 4 EXAMPLE
4 5 EXAMPLE
5 1 OTHER
6 2 OTHER
7 3 OTHER
for i, row in dftest.iterrows():
dftest.loc[i, 'new'] = row['string'][:row['position']]
In [62]: dftest
Out[62]:
position string new
0 1 EXAMPLE E
1 2 EXAMPLE EX
2 3 EXAMPLE EXA
3 4 EXAMPLE EXAM
4 5 EXAMPLE EXAMP
5 1 OTHER O
6 2 OTHER OT
7 3 OTHER OTH
EDIT
Or you could use apply
which is more convenient:
dftest.apply(lambda x: x['string'][:x['position']], axis=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.