猿问

读取CSV列,如果满足要求,写入单元格

我正在尝试读取 CSV 文件的第一列,看看它是否满足要求。如果符合要求,我想把它写到下面的一栏。


正如您从我的代码中看到的,我可以进行读取(尽管不确定是否是最好的方法),我只需要让它写入该行的第 3 列。


示例:如果第一列中的任何行包含以 25 开头的 4 位值,则在该行的第 3 列中输入 Y。


CSV 示例:


number,na,prefix25,na,na,na

1000,,,,,

1254,,,,,

251,,,,,

2501,,,,,

6548,,,,,

1478,,,,,

02,,,,,

2550,,,,,

2569,,,,,

所需的 CSV 输出:


number,na,prefix25,na,na,na

1000,,,,,

1254,,,,,

251,,,,,

2501,,y,,,

6548,,,,,

1478,,,,,

02,,,,,

2550,,y,,,

2569,,y,,,

到目前为止的代码:


def micro():

    #Prefix 25

    with open(dbPath) as f:

        reader = csv.reader(f, delimiter="\t")

        for i in reader:

            if len(i[0]) == 4:

                curStore = i[0].startswith("25")

                if curStore is True:

                    #Prints found numbers what are 4 digits and start with 25

                    print(i[0])

预先感谢您的任何帮助


肥皂起泡泡
浏览 132回答 4
4回答

holdtom

pandas是为此任务而设计的。import pandas as pddf = pd.read_csv(<path_to_file>)df['prefix25'] = df['number'].apply(lambda x: 'y' if str(x).startswith('25') else None)df.to_csv(<path_and_file_name>)

慕码人2483693

pandas这是使用的解决方案map。方法比用于列操作map更有效,而可以用于列和数据帧:applyapplyimport pandas as pd#reading the csv as a dataframe  df = pd.read_csv('test.csv', delimiter=',')#applying a lambda function using mapdf['prefix25'] = df['number'].map(lambda x: 'y' if (str(x).startswith('25') and len(str(x))==4)  else '')#replacing `NaN` with '' to match your requirements df.fillna('',inplace=True) #matching the columns as pandas automatically renames same columns df.columns = ['number','na','prefix25','na','na','na']#saving the output csvdf.to_csv('output.csv',index=False) 输出:number,na,prefix25,na,na,na1000,,,,,1254,,,,,251,,,,,2501,,y,,,6548,,,,,1478,,,,,2,,,,,2550,,y,,,2569,,y,,, 

慕村9548890

尝试执行以下易于理解的步骤:import pandas as pddf = pd.read_csv('sofile.csv',',')numlist = df.number.astype(str)outlist = ['y' if (len(x)==4 and x.startswith('25')) else ''&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for x in numlist ]df.prefix25 = outlistprint(df)输出:&nbsp; &nbsp;number&nbsp; na prefix25&nbsp; na.1&nbsp; na.2&nbsp; na.30&nbsp; &nbsp; 1000 nan&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nan&nbsp; &nbsp;nan&nbsp; &nbsp;nan1&nbsp; &nbsp; 1254 nan&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nan&nbsp; &nbsp;nan&nbsp; &nbsp;nan2&nbsp; &nbsp; &nbsp;251 nan&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nan&nbsp; &nbsp;nan&nbsp; &nbsp;nan3&nbsp; &nbsp; 2501 nan&nbsp; &nbsp; &nbsp; &nbsp; y&nbsp; &nbsp;nan&nbsp; &nbsp;nan&nbsp; &nbsp;nan4&nbsp; &nbsp; 6548 nan&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nan&nbsp; &nbsp;nan&nbsp; &nbsp;nan5&nbsp; &nbsp; 1478 nan&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nan&nbsp; &nbsp;nan&nbsp; &nbsp;nan6&nbsp; &nbsp; &nbsp; &nbsp;2 nan&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nan&nbsp; &nbsp;nan&nbsp; &nbsp;nan7&nbsp; &nbsp; 2550 nan&nbsp; &nbsp; &nbsp; &nbsp; y&nbsp; &nbsp;nan&nbsp; &nbsp;nan&nbsp; &nbsp;nan8&nbsp; &nbsp; 2569 nan&nbsp; &nbsp; &nbsp; &nbsp; y&nbsp; &nbsp;nan&nbsp; &nbsp;nan&nbsp; &nbsp;nan可以使用函数保存回 csv df.to_csv('newfile.csv')。

凤凰求蛊

这是使用temp文件的一种方法import csvimport osdef micro():&nbsp; &nbsp; #Prefix 25&nbsp; &nbsp; with open(dbPath) as f, open("temp_file", "w") as temp_outfile:&nbsp; #Please provide full path to temp file&nbsp; &nbsp; &nbsp; &nbsp; reader = csv.reader(f, delimiter="\t")&nbsp; &nbsp; &nbsp; &nbsp; writer = csv.writer(temp_outfile, delimiter="\t")&nbsp; &nbsp; &nbsp; &nbsp; for i in reader:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if len(i[0]) == 4 and i[0].startswith("25"):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i[2] = "Y"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; writer.writerow(i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; #Replace Old File with TempFile&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; os.rename("temp_file", dbPath)
随时随地看视频慕课网APP

相关分类

Python
我要回答