条件 Sum/Average/etc... Python 中的 CSV 文件
Conditional Sum/Average/etc... CSV file in Python
首先,我找到了类似的文章,但我一直无法弄清楚如何将这些问题的答案转化为我自己的问题。其次,我是 python 的新手,所以很抱歉我是菜鸟。
我的问题是:我想对文本文件中的值执行条件计算 (average/proportion/etc..)
更具体地说,我有一个看起来有点像下面的文件
0 Diamond Correct
0 Cross Incorrect
1 Diamond Correct
1 Cross Correct
到目前为止,我能够读取文件并收集所有行。
import pandas as pd
fileLocation = r'C:/Users/Me/Desktop/LogFiles/SubjectData.txt'
df = pd.read_csv(fileLocation, header = None, sep='\t', index_col = False,
name = ["Session Number", "Image", "Outcome"])
我正在查询文件,这样我就可以提出如下问题:
--当第一列('Session Number')为0时,'Outcome'列中"Correct"值的比例是多少?所以这将是 0.5,因为有一个 "Correct" 和一个 "Incorrect"。
我还有其他想要执行的计算,但是一旦我知道如何执行此操作(希望是简单的命令),我应该能够弄清楚去哪里。
谢谢!
# getting the total number of rows
total = len(df)
# getting the number of rows that have 'Correct' for 'Outcome' and 0 for 'Session Number'
correct_and_session_zero = len(df[(df['Outcome'] == 'Correct') &
(df['Session Number'] == 0)])
# if you're using python 2 you might need to convert correct_and_session_zero or total
# to float so you won't lose precision
print(correct_and_session_zero / total)
你也可以这样做:
In [467]: df.groupby('Session#')['Outcome'].apply(lambda x: (x == 'Correct').sum()/len(x))
Out[467]:
Session#
0 0.5
1 1.0
Name: Outcome, dtype: float64
它将按 Session#
对您的 DF 进行分组,并为每个组计算 Ratio of correct Outcomes
(Session#
)
首先,我找到了类似的文章,但我一直无法弄清楚如何将这些问题的答案转化为我自己的问题。其次,我是 python 的新手,所以很抱歉我是菜鸟。
我的问题是:我想对文本文件中的值执行条件计算 (average/proportion/etc..)
更具体地说,我有一个看起来有点像下面的文件
0 Diamond Correct
0 Cross Incorrect
1 Diamond Correct
1 Cross Correct
到目前为止,我能够读取文件并收集所有行。
import pandas as pd
fileLocation = r'C:/Users/Me/Desktop/LogFiles/SubjectData.txt'
df = pd.read_csv(fileLocation, header = None, sep='\t', index_col = False,
name = ["Session Number", "Image", "Outcome"])
我正在查询文件,这样我就可以提出如下问题:
--当第一列('Session Number')为0时,'Outcome'列中"Correct"值的比例是多少?所以这将是 0.5,因为有一个 "Correct" 和一个 "Incorrect"。
我还有其他想要执行的计算,但是一旦我知道如何执行此操作(希望是简单的命令),我应该能够弄清楚去哪里。
谢谢!
# getting the total number of rows
total = len(df)
# getting the number of rows that have 'Correct' for 'Outcome' and 0 for 'Session Number'
correct_and_session_zero = len(df[(df['Outcome'] == 'Correct') &
(df['Session Number'] == 0)])
# if you're using python 2 you might need to convert correct_and_session_zero or total
# to float so you won't lose precision
print(correct_and_session_zero / total)
你也可以这样做:
In [467]: df.groupby('Session#')['Outcome'].apply(lambda x: (x == 'Correct').sum()/len(x))
Out[467]:
Session#
0 0.5
1 1.0
Name: Outcome, dtype: float64
它将按 Session#
对您的 DF 进行分组,并为每个组计算 Ratio of correct Outcomes
(Session#
)