【问题标题】:Remove punctuations from list and convert string value to float in python从列表中删除标点符号并将字符串值转换为python中的浮点数
【发布时间】:2019-10-09 11:40:43
【问题描述】:

我想从列中删除美元符号和逗号并转换为浮动。 这是我到目前为止所做的,它没有工作。其实什么都没变。 数据看起来像["$200,00","$1,000.00"..."$50.00"]

import pandas as pd
import string
y_train = train.iloc[:,-1]
needtoclean=y_train.to_list()#''.join(y_train.to_list())

to_delete = set(string.punctuation) - {'$',','} 
clean = [x for x in needtoclean if x not in to_delete]

【问题讨论】:

  • 嗨,欢迎来到 stackoverflow。请提供带有您的问题的代码示例。这样可以更轻松地为您提供帮助。

标签: python python-3.x string training-data punctuation


【解决方案1】:
list_ = ['$58.00', '$60.00']       #Your Lise
new_list = []                      #Initialise new list
for elem in list_:                 #Iterate over previous list's elements
    elem = elem.replace("$", '')   #Replace the `$` sign
    new_list.append(float(elem))   #Add the typecasted float to new list

【讨论】:

    【解决方案2】:

    试试这个,下次你应该发布代码

    按索引迭代列表以便能够修改值。

    1)。删除 $

    2)。投射到浮动

    for i in xrange(len(your_list)):
        your_list[i] = float(your_list[i].replace("$", ""))
    

    【讨论】:

    • 美元符号无法替换。
    • 你为什么这么说??
    【解决方案3】:

    列表理解很容易解决。

    unclean = ['$58.00', '$125.00']  # your data
    clean = [float(value[1:]) for value in unclean if value.startswith('$')]
    # you can remove "if value.startswith('$')" if you are sure 
    # that all values start with $
    

    如果你想要它作为函数:

    unclean = ['$58.00', '$125.00']
    
    def to_clean_float(unclean):
        return [float(value[1:]) for value in unclean if value.startswith('$')]
    
    print(to_clean_float(unclean))  # Gives: [58.0, 125.0]
    

    如果您不需要它作为原子列表但想进一步处理数据,您也可以创建一个generator expression。 如果它是一个巨大的列表,它可以节省大量的内存。

    unclean = ['$58.00', '$125.00']
    
    def to_clean_float(unclean):
        return (float(value[1:]) for value in unclean if value.startswith('$'))
    
    clean_generator = to_clean_float(unclean)
    print(list(value for value in clean_generator))  # Gives: [58.0, 125.0]
    

    【讨论】:

    • 非常感谢。数据还涉及逗号。其中一些不能转换为浮动。
    • 我不喜欢基于索引的方法。 [float(value.replace("$", "").replace(",", ".")) for value in unclean] 在我看来更强大。
    【解决方案4】:

    如果美元符号总是在这些字符串中的相同位置,这应该可以完成工作。 我假设您使用 pandas 数据框。

    df["needtoclean"] = df["needtoclean"].apply(lambda x: float(x[1:].replace(",", "")))
    

    【讨论】:

    • 它有效,但我也有一个观察结果“1,000”,其中有一个逗号,它不能转换为浮动
    猜你喜欢
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多