我希望从python中的CSV文件中选择一个特定的行和列。如果值为空,我想执行一个操作,如果该值不为空,我想执行另一个操作。
我认为代码应该是这样的:
inputFile = 'example.csv'
reader = csv.reader(inputFile, 'rb')
for row in reader:
if row[5][6] == '': ==> (I mean select value the 5th row and 6th column)
(do this)
else:
(do that)
有关此主题的任何帮助或指导都会有所帮助 - 我使用列表完成了类似的任务;但是,由于CSV文件是原始的,我不知道该怎么做。
答案 0 :(得分:9)
当你想到CSV时,想想熊猫。
import pandas as pd
df = pd.read_csv('path/to/csv')
if df.iloc[5, 6]:
# do stuff
else
# do some other stuff
答案 1 :(得分:1)
您遇到的问题是,您正在查看csv文件的每一行中第5列的值索引6处的字符。相反,你想要做的是查看文件的第6行和该行的第5列
import csv
def getCell(infilepath, row, col):
with open(infilepath) as infile:
reader = csv.reader(infile)
try:
for i in range(row-1):
next(reader)
except:
print(infilepath, "does not have ", row, " rows of data")
return
try:
line = next(infilepath)
except:
print(infilepath, "does not have ", row, " rows of data")
return
col -= 1
if len(line) < col:
print(infilepath, "does not have ", col, " columns of data on row ", row)
return
return line[col]
现在我们有办法在所需的单元格中获取数据,我们可以继续:
value = getCell('example.csv', 5, 6)
if value is not None: # the value actually exists
if value == '':
# do this
else:
# do that
答案 2 :(得分:1)
试试这个:
inputFile = 'example.csv'
reader = csv.reader(inputFile, 'rb')
for i, row in enumerate(reader):
if i == 5: # here's the row 5
data = row.split(',')
if data[6]: # here's the column 6
pass # if the position [5][6] is non-empty do something
else: # otherwise
pass # do something else
答案 3 :(得分:1)
一般的想法是csv.reader只是一个特殊的文件对象,可以自动分割逗号上的内容。像任何其他文件对象一样对待它。如果你想要第n行,则迭代直到你到达第n行。
with open('inputFile', rb) as f:
reader = csv.reader(f)
for i, l in enumerate(reader):
if i==5:
try:
print l[6]
except IndexError:
print "Nothing here!"
一些注意事项:
with
块,以便在完成此代码时安全地关闭文件。您可以随时致电file.close
,但这是更好的做法。try...except
中该行的第6列,因为,可能没有第6列。比抱歉更安全。答案 4 :(得分:1)
我的names.csv文件。
len(data)
# 30
label = [1,1,1,1,1,1,1,1,1,1,,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3]
max_length = 25 # shape of data frame after removing two variables
# define the model
model = Sequential()
model.add(Dense(24, input_dim=25, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
# summarize the model
print(model.summary())
我在python中的代码
class omzettenperdag_sql_view(models.Model):
_name = "omzettenperdag_sql_view"
_auto = False
#m2o fields to retrieve data from in SQL view query:
account_invoice = fields.Many2one(comodel_name='account.invoice', readonly=True, invisible=True)
account_invoice_line = fields.Many2one(comodel_name='account.invoice.line', readonly=True, invisible=True)
#Fields returned from SQL view:
hoeveelheid = fields.Float(string="Hoeveelheid")
prijs_excl = fields.Float(string="Prijs excl. btw")
datum = fields.Datetime(String="Datum")
verkoopskanaal = fields.Char(string="Verkoopskanaal")
#Create SQL view:
def init(self, cr):
tools.drop_view_if_exists(cr, self._table)
cr.execute("""
#SQL view query here...
);
""")