比较pandas数据帧列中的多个字符串

2024-09-28 01:32:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python3.x中有以下pandas DataFrame,其中有几个数字列和两个带字符串的列:

import numpy as np
import pandas as pd

dict = {"numericvals": np.repeat(25, 8), 
    "numeric":np.repeat(42, 8), 
    "first":["beneficiary, duke", "compose", "herd primary", "stall", "deep", "regular summary classify", "timber", "property”], 
    "second": ["abcde”, "abcde”, "abcde”, "abcde”, "abcde”, "abcde”, "abcde”, "abcde”]}

df = pd.DataFrame(dict1)

df = df[['numeric', 'numericvals', 'first', 'second']]

print(df)
   numeric  numericvals                     first second
0       42           25         beneficiary, duke  abcde
1       42           25                   compose  abcde
2       42           25              herd primary  abcde
3       42           25                     stall  abcde
4       42           25                      deep  abcde
5       42           25  regular summary classify  abcde
6       42           25                    timber  abcde
7       42           25                  property  abcde

first包含一个或多个字符串。如果有多个,则用空格或逗号分隔。在

我的目标是创建一个列,记录first中字符串的长度,这些字符串的长度比second中的字符串长或短。如果这些大小相同,则应忽略此情况。在

我的想法是创建两个列表:

^{pr2}$

如果first中的字符串较长,请通过longer中的len()追加字符串长度。如果字符串较短,请通过len()short中记录字符串长度。在

以下是分析的外观(以pandas数据帧格式):

   numericvals numeric                   first second  longer  shorter
0          25      42        beneficiary, duke abcde  11       4
1          25      42                  compose abcde  7        0
2          25      42             herd primary abcde  7        4
3          25      42                    stall abcde  0        0
4          25      42                     deep abcde  0        4
5          25      42 regular summary classify abcde  7, 7, 8  0
6          25      42                   timber abcde  6        0
7          25      42                 property abcde  8        0

我不知道如何处理first中的多个字符串,尤其是如果有3个字符串。在大熊猫身上,我们应该如何做这种比较呢?在


Tags: compose字符串pandasdfnpfirstsecondprimary
1条回答
网友
1楼 · 发布于 2024-09-28 01:32:37

您可以使用pandas.DataFrame.apply(source)

import operator

def transform(df, op):
    lengths = [len(s) for s in df['first'].replace(',', ' ').split()]
    return [f for f in lengths if op(f, len(df.second))] or [0]

df['longer']  = df.apply(transform, axis=1, args=[operator.gt])
df['shorter'] = df.apply(transform, axis=1, args=[operator.lt])

这应该适用于任何数量的字符串,假设任何空格或逗号都表示新字符串。在

输出如下:

^{pr2}$

我尽力了。希望这有帮助!在

相关问题 更多 >

    热门问题