4 回答

TA貢獻1805條經(jīng)驗 獲得超10個贊
pandas是為此任務(wù)而設(shè)計的。
import pandas as pd
df = 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>)

TA貢獻1860條經(jīng)驗 獲得超9個贊
pandas
這是使用的解決方案map
。方法比用于列操作map
更有效,而可以用于列和數(shù)據(jù)幀:apply
apply
import pandas as pd
#reading the csv as a dataframe??
df = pd.read_csv('test.csv', delimiter=',')
#applying a lambda function using map
df['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 csv
df.to_csv('output.csv',index=False)?
輸出:
number,na,prefix25,na,na,na
1000,,,,,
1254,,,,,
251,,,,,
2501,,y,,,
6548,,,,,
1478,,,,,
2,,,,,
2550,,y,,,
2569,,y,,,?

TA貢獻1884條經(jīng)驗 獲得超4個贊
嘗試執(zhí)行以下易于理解的步驟:
import pandas as pd
df = pd.read_csv('sofile.csv',',')
numlist = df.number.astype(str)
outlist = ['y' if (len(x)==4 and x.startswith('25')) else ''
for x in numlist ]
df.prefix25 = outlist
print(df)
輸出:
number na prefix25 na.1 na.2 na.3
0 1000 nan nan nan nan
1 1254 nan nan nan nan
2 251 nan nan nan nan
3 2501 nan y nan nan nan
4 6548 nan nan nan nan
5 1478 nan nan nan nan
6 2 nan nan nan nan
7 2550 nan y nan nan nan
8 2569 nan y nan nan nan
可以使用函數(shù)保存回 csv df.to_csv('newfile.csv')。

TA貢獻1825條經(jīng)驗 獲得超4個贊
這是使用temp文件的一種方法
import csv
import os
def micro():
#Prefix 25
with open(dbPath) as f, open("temp_file", "w") as temp_outfile: #Please provide full path to temp file
reader = csv.reader(f, delimiter="\t")
writer = csv.writer(temp_outfile, delimiter="\t")
for i in reader:
if len(i[0]) == 4 and i[0].startswith("25"):
i[2] = "Y"
writer.writerow(i)
#Replace Old File with TempFile
os.rename("temp_file", dbPath)
添加回答
舉報