根据 pandas 数据框中的另一列获取子字符串 [英] Getting substring based on another column in a pandas dataframe

查看:51
本文介绍了根据 pandas 数据框中的另一列获取子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以基于另一列获取一列的子字符串?

Hi is there a way to get a substring of a column based on another column?

import pandas as pd
x = pd.DataFrame({'name':['bernard','brenden','bern'],'digit':[2,3,3]})
x

     digit  name
0   2   bernard
1   3   brenden
2   3   bern

我期望的是这样的:

for row in x.itertuples():
    print row[2][:row[1]]

be
bre
ber

其中的结果是基于数字的名称的子字符串.

where the result is the substring of name based on digit.

我知道我是否真的可以基于itertuples函数创建一个列表,但似乎不正确,而且我总是尝试创建向量化方法.

I know if I really want to I can create a list based on the itertuples function but does not seem right and also, I always try to create a vectorized method.

感谢任何反馈.

推荐答案

使用applyaxis=1lambda逐行使用,以便访问每一列进行切片:

Use apply with axis=1 for row-wise with a lambda so you access each column for slicing:

In [68]:
x = pd.DataFrame({'name':['bernard','brenden','bern'],'digit':[2,3,3]})
x.apply(lambda x: x['name'][:x['digit']], axis=1)

Out[68]:
0     be
1    bre
2    ber
dtype: object

这篇关于根据 pandas 数据框中的另一列获取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆