【发布时间】:2021-05-26 17:07:37
【问题描述】:
我有一个 CSV 文件,其中有一列名为“电池寿命”。数据可以是数字或附加到它的字符串。 “hr”或“hrs”是那些字符串(表示电池使用时间)。少数样本是 3hr、3hr、3hrs、3hrs 等。有一种情况是数据不可用,列值为“不可用”
这是我试图处理的数据示例。请参阅名为 Battery_life 的最后一列。 dropbox.com/s/z75wleoy3153c8o/headphonesV1-csv.csv?dl=0
我正在尝试从 CSV 列中删除 hr 和 hrs 部分。
这是我迄今为止所做的,它有效,但不是一个好的解决方案,即使我几个月前才开始编码,我也不为此感到自豪。
data = open("headphonesV1 copy.csv", "r")
# join() method combines all contents of
# csvfile.csv and formed as a string
data = ''.join([i for i in data])
# search and replace the contents
data = data.replace("hrs", "")
data = data.replace("hr", "")
# output.csv is the output file opened in write mode
x = open("headphonesV1 copy.csv", "w")
# all the replaced text is written in the output.csv file
x.writelines(data)
x.close()
我尝试的另一种方法是定义如下函数并从列中进行字符串替换。
def clean_battery_string(input_string):
if "hrs" in input_string:
clean_string = input_string.replace("hrs", '')
print(clean_string)
elif "hr" in input_string:
clean_string = input_string.replace("hr", '')
print(clean_string)
else:
clean_string = input_string
print(clean_string)
return clean_string
但我不确定如何应用此功能。有人可以帮忙吗
【问题讨论】:
标签: python python-3.x string csv replace