从列表中删除标点,并在python中将字符串值转换为浮点值

2024-04-20 13:16:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从列中去掉美元符号和逗号,并转换为浮动。 到目前为止我就是这么做的,没用。其实什么都没变。 数据看起来像[“$200,00”,“$1000.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]

Tags: to数据inimportpandasstringas符号
3条回答
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

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

按索引迭代列表以修改值。你知道吗

(1)。删除$

(2)。使漂浮

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

这很容易解决。你知道吗

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]

相关问题 更多 >