我的数据框如下所示:
test_df = pd.DataFrame({'name':['a12','b1','c'],'Length':[2,1,0]})
test_df
Length name
0 2 a12
1 1 b1
2 0 c
我想得到这样的结果:
Length name
0 2 a
1 1 b
2 0 c
使用以下代码:Getting substring based on another column in a pandas dataframe
test_df.apply(lambda x: x['name'][:-x['Length']],axis = 1)
test_df
我获得了与之前相同的数据框
Length name
0 2 a12
1 1 b1
2 0 c
答案 0 :(得分:1)
稍微修改apply
,根据len(x['name'])
-
def f(x):
return x['name'][:len(x['name']) - x['Length_to_drop']]
df.apply(f, 1)
0 a
1 b
2 c
dtype: object
答案 1 :(得分:1)
试试这个:
import pandas as pd
test_df = pd.DataFrame({'name':['a12','b1','c'],'Length':[2,1,0]})
test_df['name']=test_df.apply(lambda x: x['name'][:len(x['name'])-x['Length']],axis = 1)
test_df
这将按您的意图输出
Length name
0 2 a
1 1 b
2 0 c
答案 2 :(得分:-1)
可以使用列表函数:
outlist = list(map(lambda x,y: x[0:(len(x)-y)], test_df.name, test_df.Length_to_drop))
test_df.name = outlist
print(test_df)
输出:
Length_to_drop name
0 2 a
1 1 b
2 0 c