我有一个CSV文件,其中包含偏好实验中的评分数据。该文件相当基本,有5行,其中我需要4行(参与者,图像,流畅性,评级和版本)
我已经创建了一个Dataframe来隔离我需要的列,并且我已经通过流畅度(1和4)拆分了帧,因此我可以获得每个流畅度的组均值。
我无法弄清楚如何为每个参与者分割文件(每个人每个流利度有2个偏好评级)以获得个人评分。
以下是我的代码供参考。
我在编码时相当新,所以它可能不是最有效的方式。
由于
import pandas as pd
import numpy as np
# create dataframe from csv file and import only the colums you want
df = pd.read_csv('Pre-experiment.csv', usecols=[0,2,3,4])
pre_fluent = df[df['Fluency']== 1]
pre_disfluent = df[df['Fluency']==4]
pre_version1 = df[df['Version']==1]
pre_version2 = df[df['Version']==2]
print (pre_fluent)
print (pre_disfluent)
pre_mean_fluent = np.mean(pre_fluent)
pre_mean_disfluent = np.mean(pre_disfluent)
print (pre_mean_fluent)
print (pre_mean_disfluent)
df1 = pd.read_csv('Post-experiment.csv', usecols=[0,2,3,4])
#print (df)
post_fluent = df1[df['Fluency']== 1]
post_disfluent = df1[df['Fluency']==4]
post_version1 = df1[df['Version']==1]
post_version2 = df1[df['Version']==2]
print ("Dataframe sortted by fluency: {}".format(post_fluent))
print (post_disfluent)
post_mean_fluent = np.mean(post_fluent)
post_mean_disfluent = np.mean(post_disfluent)
print ("Post_Fluent Mean: {}".format(post_mean_fluent))
print ("Post_Disfluent Mean: {}".format(post_mean_disfluent))
答案 0 :(得分:1)
您要查找的内容并不完全清楚,但如果您需要按Participant
对数据框进行分组,请尝试使用df.set_index
将其设置为索引:
df.set_index('Participant', inplace=True)
假设您有参与者A
和B
。您可以使用df.loc
或df.iloc
获取参与者Fluency
的所有A
值(按位置而非名称引用):
fluency_A = df.loc['A']['Fluency'] # or df.loc['A', 'Fluency']
这可能取决于您的实际数据的格式,但希望它能让您接近所需的内容。
# Make up some data that we can read into our dataframe.
data = io.StringIO("""Participant,Fluency,Other
A,1,5
A,2,5
B,3,6
B,4,6""")
# Read the data, set the index, and get Fluency for "A".
df = pd.read_csv(data)
df.set_index('Participant', inplace=True)
df.loc['A']['Fluency']
# Participant
# A 1
# A 2
# Name: Fluency, dtype: int64
如评论中所述 编辑,您也可以使用df.loc['A', 'Fluency']
,但是当我有一个复杂的多索引时,我在自己的工作中遇到了一些问题。这里使用的格式:df.loc[index_specification][column_specification]
似乎对我来说更加一致。