python - 如何遍历python中的两列?

标签 python csv pandas

我正在尝试使用 python 遍历 csv 文件中的两列?我听说您必须为此导入 pandas,但我只是在编码部分苦苦挣扎。

import csv as csv
import numpy as np
import pandas as pd

csv_file_object = csv.reader(open('train.csv', 'rb'))  # Load in the csv file
header = csv_file_object.next()                   # Skip the fist line as it is a header
data=[]                                     # Create a variable to hold the data

for row in csv_file_object:                      # Skip through each row in the csv file,
    data.append(row[0:])                        # adding each row to the data variable
data = np.array(data)   



def number_of_female_in_class_3(data):
    for row in data.iterow:
        if row[2] == 'female' and row[4] == '3':
            sum += 1

问题是函数 number_of_female_in_class_3 我想遍历两个列,我想遍历第 2 列以检查行是否包含字符串 'female' 并遍历第 4 列并检查是否状态为“3”。如果这是真的,那么我想将 1 增加到 sum

我想知道是否有人可以发布有关如何完成此操作的简单代码?

这是我正在尝试检索的 train.csv 文件。

**PassengerID** | **Survived** | **Pclass**   | **Name**  |  **Sex**   |
          1     |          0   |         3    |  mary     |  Female    |
          2     |          1   |         2    |  james    |  Male      |
          3     |          1   |         3    |  Tanya    |  Female    |

谢谢

最佳答案

的确,pandas 可以在这方面为您提供帮助。

我从更干净的 CSV 开始:

PassengerID,Survived,Pclass,Name,Sex
1,0,3,mary,female
2,1,2,james,male
3,1,3,tanya,female

如果您的 CSV 实际上看起来像您发布的内容(不是真正的 CSV),那么您将有一些争论要做(见下文)。但是如果你能让 pandas 吃掉它:

>>> import pandas as pd
>>> df = pd.DataFrame.from_csv('data.csv')
>>> result = df[(df.Sex=='female') & (df.Survived==False)]

产生一个新的 DataFrame:

>>> result
             Survived  Pclass  Name     Sex
PassengerID                                
1                   0       3  mary  female

您可以执行 len(result) 来获得您想要的计数。


加载该 CSV

如果你受困于那个讨厌的 CSV,你可以像这样获取你的 df:

# Load using a different delimiter.
df = pd.DataFrame.from_csv('data.csv', sep="|")

# Rename the index.
df.index.names = ['PassID']

# Rename the columns, using X for the bogus one.
df.columns = ['Survived', 'Pclass', 'Name', 'Sex', 'X']

# Remove the 'extra' column.
del df['X']

关于python - 如何遍历python中的两列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33942067/

相关文章:

python - 当某个 channel 在 python 中上线时,如何获取 Youtube 视频 channel 的 URL?

python - TensorFlow REST 前端,但不是 TensorFlow Serving

ruby-on-rails - 无法解析 CSV 文件 - "CSV::MalformedCSVError: Unquoted fields do not allow\r or\n"

python - 更改 Pandas 条形图中的错误条标记(Caplines)

python - 当某些列列表值为空时如何合并包含列表值的列?

python - django 中的 JsonResponse 和 HttpResponse 有什么区别

python - 使用 BeautifulSoup 在脚本标签内查找键

c# - 在 C# 中解析带有标题的 CSV 文件

php - 从php中的csv文件中读取大数据

Python,数据帧 : duplicating elements in a column of lists and attributing to them rows in another column