如何处理包含字符串值的数据框列列表,获取唯一的单词

2024-10-01 19:27:14 发布

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

我试图对包含列表的数据帧列(称为dimensions)执行一些基本操作。当dataframe列包含列表时,像df['dimensions'].str.replace()这样的基本操作是否有效?这对我不起作用。我还尝试使用re.sub()方法替换列中的文本,但也不起作用

这是我的数据框中的最后一列:

**dimensions**

[50' long]    
None    
[70ft long, 19ft wide, 8ft thick]    
[5' high, 30' long, 18' wide]

这是我尝试过的,但没有成功:

def dimension_unique_words(dimensions):
if dimensions != 'None':
    for value in dimensions:
        new_value = re.sub(r'[^\w\s]|ft|feet', ' ', value)
        new_value = ''.join([i for i in new_value if not i.isdigit()])
        return new_value

df['new_col'] = df['dimensions'].apply(dimension_unique_words)

这是我从代码中获得的输出:

**new_col**

NaN    
None    
NaN    
None    
NaN    
None

我想做的是用空格替换名为dimensions的列中的数字和单位[ft,feet',],然后在该列上应用df.unique()以获得唯一的值,即[long,wide,thick,high]

预期输出为:

**new_col**

[long]    
None   
[long, wide, thick]    
[high, long, wide]

…然后我想在new_col上应用df.unique()得到[长、宽、厚、高]

怎么做


Tags: 数据nonedf列表newvaluecolnan
3条回答

首先,我们要处理的麻烦是,您的“维度”列有时是无的,有时是一个字符串元素的列表。因此,当元素为非null时,提取该元素:

df['dimensions2'] = df['dimensions'].apply(lambda col: col[0] if col else None)

接下来,获取每行中的所有字母字符串,不包括测量值:

>>> df['dimensions2'].str.findall(r'\b([a-z]+)')
0                 [long]
1                   None
2    [long, wide, thick]
3     [high, long, wide]

注意,我们使用\b单词边界(从“30ft”中排除“ft”),为了避免将\b误解为反斜杠,我们必须在正则表达式上使用r''rawstring

首先,我们要处理的麻烦是,您的“维度”列有时是无的,有时是一个字符串元素的列表。因此,当元素为非null时,提取该元素:

df['dimensions2'] = df['dimensions'].apply(lambda col: col[0] if col else None)

接下来,获取每行中的所有字母字符串,不包括测量值:

>>> df['dimensions2'].str.findall(r'\b([a-zA-Z]+)')
0                 [long]
1                   None
2    [long, wide, thick]
3     [high, long, wide]

注意,我们使用\b单词边界(从“30ft”中排除“ft”),为了避免将\b误解为反斜杠,我们必须在正则表达式上使用r''rawstring

这会给你一个列表。您需要一个集合,以防止重复发生,因此:

 df['dimensions2'].str.findall(r'\b([a-zA-Z]+)').apply(lambda l: set(l) if l else None)
0                 {long}
1                   None
2    {thick, long, wide}
3     {high, long, wide}
  1. 使用str.findall查找列表中的所有维度值
  2. 使用explode将列表分解为具有相同索引的元素
  3. 然后使用groupby(level=0).unique()将重复项按索引放到列表中
df['new_col'] = (
  df['dimensions'].fillna('').astype(str)
 .str.findall(r'\b[a-zA-Z]+\b')
 .explode().dropna()
 .groupby(level=0).unique()
)

使用df['new_col'].explode().dropna().unique()获取唯一的维度值

array(['long', 'wide', 'thick', 'high'], dtype=object)

相关问题 更多 >

    热门问题