【问题标题】:Remove last character of specific rows ending with '.'删除以 '.' 结尾的特定行的最后一个字符
【发布时间】:2019-06-18 04:56:08
【问题描述】:

我有多个具有相同类型数据的 csv 文件要合并到行上以形成单个数据框,但某些行名称包含脏数据。

例如'.'在实际名称的末尾。 我尝试了以下代码-

for file in all_files:
temp = pd.read_csv(file, encoding = "unicode_escape")
temp = temp[['S.No.', 'Item', '2014-15']]
state = lambda x: x.split('-')
temp.rename(columns = {'2014-15':state(file)[1]}, inplace= True)
if file == all_files[0]:
    all_states = temp.copy(deep=True)
else:
    temp["Item"] = temp["Item"].str.replace("*", "")
    all_states = pd.merge(all_states, temp, how = 'outer', on = ['S.No.', 'Item'])
del temp

我得到的输出是 -

S.No. 1 1.1 1.2 1.3 . . .

1.1。 --> 需要摆脱这些并将它们视为 1.1

被污染的 S.No.为单个列形成一个新行。我需要它与其他人在同一行。

我只想要最后一个'.'在要删除的字符串的末尾,而不是全部。

我尝试了以下方法来清理 S.No. :

temp["S.No."] = temp["S.No."].str.rstrip(".")
temp["S.No."] = temp["S.No."].str.replace(".$", "")
temp["S.No."] = re.sub(r".$", "", str(temp["S.No."]))

但它们都不起作用。

标题:

脏行:

【问题讨论】:

  • 试试temp["S.No."] = temp["S.No."].astype(int)

标签: python regex python-3.x pandas dataframe


【解决方案1】:

假设您只删除一个.(如果它存在于字符串末尾):

def clean_s_no(text):
    return re.sub('\.$', '', text)

注意\(转义字符)和$(字符串结尾)。

然后,将该函数应用于该列的所有行:

temp["S.No."] = temp["S.No."].apply(lambda x: clean_s_no(x), axis=1)

temp["S.No."] = temp["S.No."].apply(clean_s_no, axis=1)

【讨论】:

  • 我只想删除作为字符串结尾字符的点,而不是全部。
  • @ShreyasPara 我已根据您的说明修改了我的答案。
  • 谢谢 Zac,但它给了我一个错误 - TypeError: clean_s_no() got an unexpected keyword argument 'axis' 如果我删除 'axis',它什么也不做。
  • Zac,您的代码或我尝试的代码没有问题。该文件有一个问题,“。”不是最后一个字符,它有四个尾随空格。
  • @ShreyasPara 我建议使用regexr.com 找出与您要查找的内容匹配的适当正则表达式。
【解决方案2】:

假设您是“S.No.”列是字符串类型,然后尝试以下操作:

temp.loc[temp["S.No."].str.contains('.'), 'S.No.'] = temp["S.No."].str.replace(".","")

您可以通过以下方式将列类型更改为字符串

temp["S.No."] = temp["S.No."].astype(str)

【讨论】:

  • 它是一个字符串,但只有其中一些有'.'在需要删除的末尾。
  • 这个 "temp.loc[temp["S.No."].str.contains('.'), 'S.No.']" 部分只会选择那些有 '. '在它们中,然后这个 "temp["S.No."].str.replace(".","")" 部分将替换 '.'为空白。我希望这是有道理的。
【解决方案3】:

问题是'.'最后还有另外 4 个尾随空格未被注意到。

所以在删除这些空格后 -

temp["S.No."] = temp["S.No."].str.strip()

所有提到的方法都有效。 我用过-

temp["S.No."] = temp["S.No."].str.rstrip(".")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多