python - Pandas : extracting column1's value at column2th position

标签 python string pandas dataframe

我有一个数据框,其中有两列,一列是字符串列,一列是整数列。

column1  column2
 abcdef        2
  gtihj        4
  jiuwq        3

我想要另一个column3,其column1的值位于col2位置,如下所示

column1    column2   column3    
abcdef     2         b
gtihj      4         h
jiuwq      3         u

我尝试了以下代码

result['column1'].str.get(result['column2'])

但出现以下错误

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

最佳答案

生成错误是因为 str.get 需要标量索引,而不是索引列表/可迭代(它不理解这种输入,也不知道如何处理它) 。

在这种情况下,列表理解可以解决问题 -

df['column3'] = [i[j - 1] for i, j in zip(df.column1, df.column2)]

df    
  column1  column2 column3
0  abcdef        2       b
1   gtihj        4       h
2   jiuwq        3       u

这个问题从根本上来说很难向量化,因此以 C 速度运行的列表理解是一个非常高性能的替代方案。

较慢的替代方案包括(为了完整性),apply

df['column3'] = df.apply(lambda x: x.column1[x.column2 - 1], 1)

df    
  column1  column2 column3
0  abcdef        2       b
1   gtihj        4       h
2   jiuwq        3       u

np.vectorize:

f = np.vectorize(lambda x, y: x[y - 1])
df['column3'] = f(df.column1, df.column2)

df
  column1  column2 column3
0  abcdef        2       b
1   gtihj        4       h
2   jiuwq        3       u

关于python - Pandas : extracting column1's value at column2th position,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49248488/

相关文章:

python - 将概率分布拟合到数据并找到它的累积分布函数

Python 循环不应该工作但仍然可以工作

java - 用于将字符序列转换为字符串的流的替代方案

java - 为什么 Sun 指定 String.hashCode() 实现?

Java排序数组集合到字符串

python-3.x - 如何将tqdm与Dataframes的 map 一起使用

python - Pandas 数据框过滤多个条件

python - 使用 LSTM 和 keras 进行时间序列预测的分类变量

python - "unstack"包含多行列表的 pandas 列

python - 很好地从 Python Interpreter 复制