我在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个字符串。在大熊猫身上,我们应该如何做这种比较呢?在
您可以使用
pandas.DataFrame.apply
(source):这应该适用于任何数量的字符串,假设任何空格或逗号都表示新字符串。在
输出如下:
^{pr2}$我尽力了。希望这有帮助!在
相关问题 更多 >
编程相关推荐