【问题标题】:Using the value from one column to slice the value of another column to generate a new column in Pandas [duplicate]使用一列中的值对另一列的值进行切片以在 Pandas 中生成一个新列 [重复]
【发布时间】:2020-02-19 08:53:08
【问题描述】:

我真正的 pandas 数据框有 500,000 行和 20 列。我想使用一列中的信息对另一列中的值进行切片并返回包含此信息的新列。下面是我的数据框和所需输出的简化版本。我需要使用“位置”中保存的值来知道在哪里切“句子”以返回我正在寻求分析“动物”的信息。为简单起见,位置值和位置值减3给出拼接坐标:对于位置值6,所需信息(动物)是句子[3:6]。

我一直在努力使用不同的方法,包括对行进行迭代(iterrowsitertuples)(有人提到的“很少正确”),但我担心我不知道如何正确执行此操作其他人说“永远不要迭代”并强调它的问题,并“用尽其他选择”。但我不知道选项,就我到目前为止,切片不是那么简单吗?最安全、最专业的方法是什么?我不在乎速度。我关心准确性。

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


【解决方案1】:

试试:

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

【讨论】:

  • 谢谢大家! Aryrez 的答案对我不起作用,直到我取出 .str,就像在重复的答案中所做的那样。'df['animal'] = df.apply(lambda x: x['sentence'][x[' location'] - 3 : x['location']], axis=1)'
  • @MelBel88 对,我的错。 .str 仅在 pd.Series 上需要,而 x 是单个字符串。我已经为下一代编辑了它:)
  • 谢谢!我在这里学到了很多东西。欣赏!
猜你喜欢
  • 2018-03-01
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 2022-10-21
相关资源
最近更新 更多