我遇到了一个问题:
import pandas
df=pandas.DataFrame([['ab','b'],['cc','d'],['ab','d']],columns=['id','table'])
像这样的df:
id table
0 ab b
1 cc d
2 ab d
我想得到结果:
id table gram
0 ab b select ab from b
1 cc d select cc from d
2 ab d select ab from d
我尝试使用str方法来获得结果,但我不知道如何转换StringMethods'反对str。谢谢!
答案 0 :(得分:2)
您可以使用:
df['gram'] = 'select ' + df.id + ' from ' + df.table
print (df)
id table gram
0 ab b select ab from b
1 cc d select cc from d
2 ab d select ab from d
使用apply
的解决方案,但速度很慢:
df['gram'] = df.apply(lambda x: "select {} from {}".format(x.id, x.table), axis=1)
import pandas
df=pandas.DataFrame([['ab','b'],['cc','d'],['ab','d']],columns=['id','table'])
#[30000 rows x 2 columns]
df = pd.concat([df]*10000).reset_index(drop=True)
#print (df)
In [34]: %timeit df['gram'] = 'select ' + df.id + ' from ' + df.table
100 loops, best of 3: 12.6 ms per loop
In [35]: %timeit df['gram1'] = df.apply(lambda x: "select {} from {}".format(x.id, x.table), axis=1)
1 loop, best of 3: 1.42 s per loop