for循环导出csv的条件语句

时间:2018-04-17 15:56:01

标签: python python-3.x pandas

我正在使用python将CSV文件转换为数据框。数据框如下所示: enter image description here

我的任务是搜索此数据框中的所有行,并找到这样的值(startlat应位于18到20之间,startlon应介于72.5到75之间)。当我找到这些值时,我必须将这些特定的行导出为单独的csv。我已经在python中完成了从dataframe中提取lat和lon数据的代码:

import pandas as pd
# read in data to use for plotted point

############################# Open your csv file ################################
dataset = pd.read_csv('MyData.csv', delimiter = ',')
a=len(dataset.index)                                           # "a" is number of rows CSV has 
print(a)
################################################################################
for i in range(0,a):

    start_latitude=str(dataset.iloc[i,2])
    start_longitude=str(dataset.iloc[i,3])

如何创建一个条件,使其导出start_latitude介于18和20之间,start_longitude介于72.5到75之间的整个行

1 个答案:

答案 0 :(得分:2)

这可能对您有用:

import pandas as pd

dataset = pd.read_csv('MyData.csv', delimiter = ',')

# Set filter conditions beforehand.
condition_1 = (18 >= dataset['StartLat']) & (20 <= dataset['StartLat'])
condition_2 = (72.5 >= dataset['StartLng']) & (75 <= dataset['StartLng'])

# Filter based on conditions.
filtered_dataset = dataset[condition_1 & condition_2]

# Export filtered dataset.
filtered_dataset.to_csv(...)