【问题标题】:Iterative loop to remove specific unwanted characters from a string从字符串中删除特定不需要的字符的迭代循环
【发布时间】:2020-12-13 09:58:22
【问题描述】:

我想在数据框中获取字符串“APPLES_10_4”并将其变为“APPLES”。我想出的代码如下:

import pandas as pd
data = ['APPLES_10_4']

Name_Parameters = []
df = pd.DataFrame(data, columns = ['fruit'], index = ['count'])

    
def badletters(lastletter):
    badletters = ["1","2","3","4","5","6","7","8","9","_"]
    if lastletter in badletters:
        return True
    else:
        return False   

def stripe(variable):
    tempStrippedVariable = variable
    foundEndVariable = False
    while not foundEndVariable:
        lastletter = tempStrippedVariable [:-1]
        if badletters(lastletter):
            tempStrippedVariable = tempStrippedVariable [:-1]
        else:
            foundEndVariable = True
    strippedVariable = tempStrippedVariable
    return strippedVariable

for variable in df:
strippedVariable = stripe(str(variable))
prefixes = []
if strippedVariable not in prefixes:
    prefixes.append(strippedVariable)
print(df)

我得到的输出是带有 ['APPLES_10_4'] 的原始数据框,而不是显示 ['APPLES'] 的更改后的数据框。

【问题讨论】:

  • 为什么不使用re.sub()
  • prefixes 由什么组成?
  • prefixes 将是整个数据框,其中包含其他字符串,例如“mangoes_1_5”,因此前缀应该是水果名称数组,没有任何“badletters”
  • 错误是因为数据框包含数字,而不仅仅是字符串。
  • 试试for variable in df: print(variable),你就会看到它们。

标签: python for-loop typeerror


【解决方案1】:

一些数据框元素是整数,而不是字符串。您可以在调用stripe()之前将它们转换为字符串

for variable in df:
    strippedVariable = stripe(str(variable))
    if strippedVariable not in prefixes:
        prefixes.append(strippedVariable)
print(prefixes)

或者你可以跳过它们。

for variable in df:
    if not isinstance(variable, str):
        continue
    strippedVariable = stripe(variable)
    if strippedVariable not in prefixes:
        prefixes.append(strippedVariable)
print(prefixes)

另一个错误在stripe():

lastletter = tempStrippedVariable [:-1]

应该是

lastletter = tempStrippedVariable [-1]

您将lastletter 设置为整个字符串除了最后一个字母。

但是整个函数可以简单地替换为:

def stripe(variable):
    badletters = ["1","2","3","4","5","6","7","8","9","_"]
    return variable.rstrip(badletters)

最后,for variable in df 不会遍历数据框内容,只是遍历列名。见How to iterate over rows in a DataFrame in Pandas

for row in df.itertuples():
    variable = row[0]
    strippedVariable = stripe(variable)
    if strippedVariable not in prefixes:
        prefixes.append(strippedVariable)

【讨论】:

  • 我将代码更改为您在上面所做的,但我得到的输出是数据框列名称 ['fruits'] 而不是更改后的字符串 'APPLES'。
  • 如果你只做print(variable),你会看到什么?
  • print(variable) 输出结果
  • 问题在于for 循环,它只是遍历列名,而不是数据。
  • 我将列名更改为“fruit_10_4”,看看它是否至少剥离了“badletters”,但事实并非如此。这是否意味着我的条带功能也不起作用。除了我迭代列名的问题
猜你喜欢
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
  • 2016-06-29
  • 2015-08-06
  • 1970-01-01
  • 2011-02-16
相关资源
最近更新 更多