【发布时间】:2020-02-19 08:53:08
【问题描述】:
我真正的 pandas 数据框有 500,000 行和 20 列。我想使用一列中的信息对另一列中的值进行切片并返回包含此信息的新列。下面是我的数据框和所需输出的简化版本。我需要使用“位置”中保存的值来知道在哪里切“句子”以返回我正在寻求分析“动物”的信息。为简单起见,位置值和位置值减3给出拼接坐标:对于位置值6,所需信息(动物)是句子[3:6]。
我一直在努力使用不同的方法,包括对行进行迭代(iterrows 和 itertuples)(有人提到的“很少正确”),但我担心我不知道如何正确执行此操作其他人说“永远不要迭代”并强调它的问题,并“用尽其他选择”。但我不知道选项,就我到目前为止,切片不是那么简单吗?最安全、最专业的方法是什么?我不在乎速度。我关心准确性。
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
【问题讨论】:
-
这是否意味着动物的名字永远只有三个字母长?
-
是的,总是三个字母。
-
python def process_row(row, offset=3): label = row['sentence'] pos = row['location'] animal = label[pos-offset:pos] return animal df['animal'] = df.apply(lambda x: process_row(x, offset=3), axis=1) print(df)
标签: python pandas iteration text-processing