【问题标题】:Remove single letters from strings in Pandas dataframe从 Pandas 数据框中的字符串中删除单个字母
【发布时间】:2017-06-03 19:30:02
【问题描述】:

我有一个 DataFrame,其中的一列用字符串填充。我想从列中删除任何单个字母的外观。到目前为止,我已经尝试过:

df['STRI'] = df['STRI'].map(lambda x: " ".join(x.split() if len(x) >1)

我想输入ABCD X WYZ得到ABCD WYZ

【问题讨论】:

  • 您的支票是关于整个字符串的。对每个单词都这样做:df['STRI'].map(lambda x: ' '.join(word for word in x.split() if len(word)>1)) 虽然可能有更好的方法来做到这一点。

标签: python string pandas


【解决方案1】:

试试这个:

df['STRI'] = npi['STRI'].str.replace(r'\b\w\b', '').str.replace(r'\s+', ' ')

例如:

import pandas as pd

df = pd.DataFrame(data=['X ABCD X X WEB X'], columns=['c1'])
print df, '\n'
df.c1 = df.c1.str.replace(r'\b\w\b', '').str.replace(r'\s+', ' ')
print df

输出:

                 c1
0  X ABCD X X WEB X 

           c1
0   ABCD WEB 

【讨论】:

  • 这不是一概而论,因为原始问题要求删除任何单个字符。
  • 再试一次。谢谢@piRSQuared。
  • 修改后又试了一次,还是不行。
  • 可以包含npi.head()df.head() 吗?
  • @piRSquared 这不会处理边缘情况。
【解决方案2】:

您可以使用str.replace 和正则表达式。模式\b\w\b 将用单词边界替换任何单个单词字符。请参阅下面的工作示例:

使用系列的示例:

s = pd.Series(['Katherine','Katherine and Bob','Katherine I','Katherine', 'Robert', 'Anne', 'Fred', 'Susan', 'other'])

   s.str.replace(r'\b\w\b','').str.replace(r'\s+', ' ')

0            Katherine
1    Katherine and Bob
2            Katherine
3            Katherine
4               Robert
5                 Anne
6                 Fred
7                Susan
8                other
dtype: object

你的测试数据的另一个例子:

    s = pd.Series(['ABCD','X','WYZ'])

0    ABCD
1       X
2     WYZ
dtype: object

s.str.replace(r'\b\w\b','').str.replace(r'\s+', ' ')

0    ABCD
1        
2     WYZ
dtype: object

你的数据是:

df['STRI'].str.replace(r'\b\w\b','').str.replace(r'\s+', ' ')

【讨论】:

  • .strip() 将仅替换前面和结尾的空格。中间的空格将被省略。
【解决方案3】:

列表理解

[
    ' '.join([i for i in s.split() if len(i) > 1])
    for s in npi.STRI.values.tolist()
]

str.split

s = npi.STRI.str.split(expand=True).stack()
s[s.str.len() > 1].groupby(level=0).apply(' '.join)

【讨论】:

  • .str.replace().str.replace() 会高效吗?
  • @MYGz 使用应用并将两个替换嵌入到同一个应用中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
  • 1970-01-01
  • 1970-01-01
  • 2018-02-24
相关资源
最近更新 更多