我正在尝试使用 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']
我是一名优秀的程序员,十分优秀!