使用一列的值对另一列的值进行切片以在 Pandas 中生成一个新列

Using the value from one column to slice the value of another column to generate a new column in Pandas

我真正的 pandas 数据框有 500,000 行和 20 列。我想使用一列中的信息来分割另一列中的值,并 return 一个包含此信息的新列。下面是我的数据框和所需输出的简化版本。我需要使用 'location' 中保存的值来知道在哪里将 'sentence' 切片到 return 我正在寻求分析的信息 'animal'。为了简单起见,location值和location值减3给出拼接坐标:对于6个想要的信息(动物)的location值是sentence[3:6].

我一直在努力使用不同的方法,包括在行上迭代(iterrowsitertuples)(有人提到的是 "rarely correct"),但我担心我没有知道如何正确地做到这一点,因为其他人说“从不迭代”并强调它的问题,并 "exhaust other options"。但我不知道这些选项,就我目前所知,切片不是那么简单吗?最安全、最专业的方法是什么?我不在乎速度。我关心准确性。

my_dict = {'sentence': [ 'Thedogwearsred', 'Thatcatatethebird', 'Thebigratstruggledwithpandas', 'Thebestdogwassmall'], 'location' = [6, 7, 9, 10]}
df = pd.DataFrame(my_dict)
Out[50]: 
                       sentence  location
0                Thedogwearsred         6
1             Thatcatatethebird         7
2  Thebigratstruggledwithpandas         9
3            Thebestdogwassmall        10

期望的输出:

Out[52]: 
                       sentence  location animal
0                Thedogwearsred         6    dog
1             Thatcatatethebird         7    cat
2  Thebigratstruggledwithpandas         9    rat
3            Thebestdogwassmall        10    dog

尝试:

df['animal'] = df.apply(lambda x: x['sentence'][x['location'] - 3 : x['location']], axis=1)