1

I'm a beginner with Python. I have a csv file with a single column of numbers, I have to find all the numbers that are greater than the previous and the following. I don't understand how I can apply a for-loop to the file column.

The code I tried is the following:

import pandas as pd

pf = pd.read_csv(r'C:\Users\Fra\Desktop\IO.csv')
print(pf)

results = []
for column in pf:
    for i in range(len(column)):
        if(x[i]>x[i-1] and x[i]>x[i+1]):
             results.append(x[i])

print(results)
smci
  • 32,567
  • 20
  • 113
  • 146

1 Answers1

0

Assume you file is of the following format:

4
7
5
3
4
...

You do not have to use panda:

bucket = []

with open(filename) as f:
    for line in f:
        item = int(line)
        bucket.append(item)

results = []

for i in range(1, len(bucket) - 1): # iterate from second to the second last item
    a = bucket[i-1]
    b = bucket[i]
    c = bucket[i+1]
    if b > a and b > c:
        results.append(b)

In case you really want to use panda:

import pandas as pd

pf = pd.read_csv(filename)
pf.astype(int)

results = []

for i in range(1, len(pf) - 1): # iterate from second to the second last item
    a = pf.loc[i-1][0]    # 0 here is the header name
    b = pf.loc[i][0]      # As we have no header, it is 0, indicating the first column
    c = pf.loc[i+1][0]

    if b > a and b > c:
        results.append(b)

Reference: How to get a value from a cell of a dataframe?

Chan Echo
  • 38
  • 1
  • 3