[英]Apply a loop to a column of a CSV file
我是 Python 的初学者。 我有一个带有单列数字的 csv 文件,我必须找到所有大于前一个和下一个数字的数字。 我不明白如何将 for 循环应用于文件列。
我尝试的代码如下:
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)
假设您的文件具有以下格式:
4
7
5
3
4
...
您不必使用熊猫:
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)
如果您真的想使用熊猫:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.