从 Pandas Dataframe 列中删除重复的逗号换句话说,我只需要列中的文本用逗号分隔

Removing repeated commas from Pandas Dataframe Column in other words I just need the text from the column with a comma separating them

我有这个数据框 Text

Text Cleaned Col
, , , Apples , , , Hard Work , , Apples, Hard Work
, , , , , , , , Apples , , , , , Apples
Apples , , Watermelon , , , , , , Apples, Watermelon
, , , , , , , , , , , , , , , , ,

我想创建一个列,例如 Cleaned Col,基本上使用正则表达式。

我查看了不同的模式,例如 r'\s*,*([^(a-zA-Z)]*)',但我没有得到正确的结果。

使用Series.str.findall获取单词并用逗号连接:

df['Cleaned Col'] = df['Text'].str.findall('\w+').str.join(', ')
print (df)
                                      Text         Cleaned Col
0      , , , Apples , , , Bananas , , ,        Apples, Bananas
1    , , , , , , , , Apples , , , , ,                   Apples
2        Apples , , Watermelon , , , , , ,  Apples, Watermelon
3  , , , , , , , , , , , , , , , , ,                          

你可以试试把逗号换成空格,然后清空左右空格,把中间的空格换成逗号:

df['Cleaned Col'] = df['Text'].apply(lambda x: x.replace(',', ' ').lstrip().rstrip().replace(' ', ', ')

由于您的字段是逗号分隔的,因此您可以使用

# If the fields CANNOT contain whitespace:
df['Cleaned Col'] = df['Text'].str.findall(r'[^\s,]+').str.join(', ')

# If the fields can contain whitespace:
df['Cleaned Col'] = df['Text'].str.findall(r'[^\s,](?:[^,]*[^\s,])?').str.join(', ')

正则表达式提取所有找到的匹配项,然后 .str.join(', ') 将结果列表项连接成一个字符串。正则表达式 (see its demo) 表示:

  • [^\s,]+ - 一个或多个 除空格和逗号以外的字符
  • [^\s,] - 单个 字符而不是空格和逗号
  • (?:[^,]*[^\s,])? - 可选择出现除逗号以外的任何零个或多个字符,然后是除空格和逗号以外的字符。

如果你的逗号用空格填充并且你真的想使用 Series.str.replace,你可以使用

df['Cleaned Col'] = df['Text'].str.replace(r'^[\s,]+|[\s,]+$|(\s)*(,)[\s,]*', r'', regex=True)

参见 this regex demo

详情:

  • ^[\s,]+ - 字符串开头的一个或多个空格或逗号
  • [\s,]+$ - 字符串末尾的一个或多个空格或逗号
  • (\s)*(,)[\s,]* - 零个或多个空格(最后一个匹配的保留在第 1 组,</code>),然后是一个逗号(捕获到第 2 组,<code>),然后零个或多个空格或逗号字符。

替换为第 2 组 + 第 1 组值。