【问题标题】:Get first half of string from pandas dataframe column从熊猫数据框列中获取字符串的前半部分
【发布时间】:2021-08-12 07:28:01
【问题描述】:

我想从 pandas 数据框列中获取字符串的前半部分,其中长度逐行变化。我四处搜索并找到了questions like this,但解决方案都集中在分隔符和正则表达式上。我没有分隔符 - 我只想要字符串的前半部分,不管它有多长。

我可以指定我想要的字符串长度:

import pandas as pd

eggs = pd.DataFrame({"id": [0, 1, 2, 3],
                     "text": ["eggs and spam", "green eggs and spam", "eggs and spam2", "green eggs"]})

eggs["half_length"] = eggs.text.str.len() // 2

然后我想做一些事情,比如eggs["truncated_text"] = eggs["text"].str[:eggs.half_length]。还是首先定义此列是错误的方式?有人可以帮忙吗?

【问题讨论】:

  • 你对前半部分的定义是什么,包括在计数中吗?如果你有三个词,你会如何定义一半?

标签: python pandas string


【解决方案1】:

您可以将函数应用于text 列:

import pandas as pd

eggs = pd.DataFrame({"id": [0, 1, 2, 3],
                     "text": ["eggs and spam", "green eggs and spam", "eggs and spam2", "green eggs"]})

eggs['truncated_text'] = eggs['text'].apply(lambda text: text[:len(text) // 2])

输出

|   id | text                | truncated_text   |
|-----:|:--------------------|:-----------------|
|    0 | eggs and spam       | eggs a           |
|    1 | green eggs and spam | green egg        |
|    2 | eggs and spam2      | eggs an          |
|    3 | green eggs          | green            |

【讨论】:

    【解决方案2】:

    您可以使用比 .apply 方法更快的矢量化操作来执行此操作。我读了这篇有趣的文章,它更深入地解释了矢量化操作https://realpython.com/fast-flexible-pandas/

    可以在以下帖子中找到对字符串使用矢量化操作的示例:Pandas make new column from string slice of another column

    【讨论】:

      猜你喜欢
      • 2013-07-21
      • 1970-01-01
      • 2017-09-09
      • 2017-07-08
      • 1970-01-01
      • 2016-05-17
      • 2021-01-31
      • 1970-01-01
      • 2021-07-16
      相关资源
      最近更新 更多