从“string1234”中剥离字符串

2024-04-26 01:39:17 发布

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

我是python新手,我想在我的数据挖掘研究中使用这种漂亮的语言。 我现在手头上有一个大数据文件,不幸的是,示例标识被定义为附加在数字上的字符串,如下所示:

A、B1、B2、B3、C1、C2、C3
0.2,0.456,0.7,1.01,0.91,0.11,0.31

为了构建一个有用的分类器,我需要从字母中去掉数字,这样我就可以设置一个目标,即

集合(['A','B','C'])

我首先需要做的是创建一个带有剥离头的输出,这样新的csv文件应该是:

A,B,B,B,C,C
0.2,0.456,0.7,1.01,0.91,0.11,0.31

因为我拥有的文件非常庞大,所以我想从函数中浏览大数字列,并从数字中去掉它们的标题。可能代码的作用如下:

import numpy as np
import pandas as pnda
#from sklearn.linear_model import Ridge, Lasso
import string
import csv
import os

# Please don't pay attention to the first part of the code, it is just to load the file 

def get_file_path(filename):
    drkt = os.getcwd()
    file_path = os.path.join(drkt,filename)

    return file_path
    file_path = get_file_path('testing.csv')


def read_csv(file_path):
    data_file = open(file_path, 'rU')
    reader = csv.reader(data_file)
    headers_=reader.next()
print headers_ # Just to see the lines

这当然是一个非常原始的代码,但我只想演示一下我卡住的地方。我基本上只想用“strip(”0123456789=,“)”作为标题‘row’,但我不知道如何达到这一点。我设法剥离的标题,但我发现我的代码拉出来,并剥离整个列这不是我想要的,我也就是说,我想剥离每个csv日期文件的第一行。你知道吗

请接受我的道歉,如果我的信息很长或如果我没有解释好我的观点。你知道吗

期待你的消息


Tags: 文件csvthetopath代码import标题
3条回答

用正则表达式把它们剥离出来怎么样?你知道吗

这个将从头中删除所有整数。你知道吗

import re
col = "A2"

re.sub(r"\d","",col)

输出

A

对你来说

headers_=reader.next()
headers_ = [re.sub(r"\d","",col) for col in headers_]
# do something with headers_

正如斯瓦尔登所说的,你就快到了

import csv

def read_csv(file_path):
    data_file = open(file_path, 'rU')
    reader = csv.reader(data_file)
    headers_=reader.next()
    print headers_ # ['A', ' B1', ' B2', ' B3', ' C1', ' C2', ' C3']

    # Process headers outside of loop
    headers_ = [col.strip("0123456789=,") for col in headers_]
    print headers_ # ['A', ' B', ' B', ' B', ' C', ' C', ' C']

    for row in reader:
        # do what you want with the data rows

我不完全理解你的要求,但你是在寻找这样的功能?你知道吗

 def remove_numbers(l):
     #Create string to use for output
     output = "";
     #loop through the input string
     for x in l:
        #Test to see what characters are NOT digits
         if not x.isdigit():
            #If it isn't a digit add it to the output string
            output += x
    #Return the output string
    return output

此函数接受字符串作为输入,并删除作为数字的字符。运行这个输入A, B1, B2, B3, C1, C2, C3得到这个输出'A, B, B, B, C, C, C'。我想你可以在做其他处理之前运行这个。你知道吗

编辑:正则表达式也可以用来实现这个目标

相关问题 更多 >