【问题标题】:Pandas CSV averaging and sortingPandas CSV 平均和排序
【发布时间】:2015-10-08 02:40:52
【问题描述】:

对于我最后的 Python 计算任务,我被要求用 Python 编写一个数据库程序,这将允许我访问三个班级数据库,每个班级数据库都包含一个参加算术测验的学生的三个分数。必须对代码进行三种排序方式;按字母顺序使用名字,作为平均值,将所有三个分数相加并除以三以找到唯一值,然后将分数从最高分到最低分排序。 因此假设以下是否为 CSV 文件之一:

name1       name2 score1 score2 score3
Atticus     Finch 9      8      10
Jem         Finch 5      7      6
Jean Louise Finch 3      2      4

如果最终用户希望它按字母顺序排序,这就是它在 Python IDLE GUI 上的样子:

Atticus     Finch 9      8      10
Jean Louise Finch 3      2      4
Jem Finch   Finch 5      7      6

如果最终用户希望将其按平均排序,则应如下所示:

Atticus     Finch 9
Jem         Finch 6
Jean Louise Finch 3

如果最终用户希望它从高到低排序,它应该是这样的:

Atticus     Finch 10     9      8
Jem         Finch 7      6      5
Jean Louise Finch 4      3      2

现在这是我的代码当前的样子:

print("Welcome to the Database sorter. The system works based on the following functions. Choose your class by inputting a letter, and choose the method of sorting the data by inputing a number afterwards. A is for Class A, B is for Class B and C is the Class C.1 is for soritng the data as an average, 2 is for sorting the data in alphabetical order and 3 is for sorting the data from highest to lowest.")

classanddatasorter =''
while classanddatasorter not in ["A1","A2","A3","B1","B2","B3","C1","C2","C3"]:
classanddatasorter = input("You have the following nine options. Input A1 to sort the results of Class A as an average. Input A2 to sort the results of Class A in alphabetical order. Input A3 to sort the results of Class A from highest to lowest. Input B1 to sort the results of Class B as an average. Input B2 to sort the results of Class B in alphabetical order. Input B3 to sort the results of Class B from highest to lowest. Input C1 to sort the results of Class C as an average. Input C2 to sort the results of Class C in alphabetical order. Input C3 to sort the results of Class C from highest to lowest. ")
if classanddatasorter == "A1":
 df = pd.read_csv('classa.csv')
 df[["score1", "score2","score3"]].mean(axis=1)

elif classanddatasorter == "A2":
 df = pd.read_csv('classa.csv')
 saved_column = df.column_name
 name = df.name
 name.sort 

elif classanddatasorter == "A3":
 df = pd.read_csv('classa.csv')
 df.sort[('score1','score2','score3'], ascending=False) 

elif classanddatasorter == "B1":
 df = pd.read_csv('classb.csv')
 df[["score1", "score2","score3"]].mean(axis=1)  

elif classanddatasorter == "B2":
 df = pd.read_csv('classb.csv')
 saved_column = df.column_name
 name = df.name

elif classanddatasorter == "B3":
 df = pd.read_csv('classb.csv')
 df.sort[('score1','score2','score3'], ascending=False)

elif classanddatasorter == "C1":
 df = pd.read_csv('classc.csv')
 df[["score1", "score2","score3"]].mean(axis=1)

elif classanddatasorter == "C2":
 bamboo = pd.read_csv('classc.csv')
 saved_column = df.column_name
 name = df.name
 name.sort 

elif classanddatasorter == "C3":
 df = pd.read_csv('classc.csv')
 df.sort[('score1','score2','score3'], ascending=False)

到目前为止,我收到以下错误:

尝试对代码进行平均排序:

 Traceback (most recent call last):
  File "C:\Users\MVMCJK\Downloads\Python code\Seperate independent draft of Task 3 (not intergated with Task 1 and 2) draft 3.py", line 70, in <module>
df[["score1", "score2","score3"]].mean(axis=1)
  File "C:\Users\MVMCJK\Anaconda3\lib\site-packages\pandas\core\frame.py", line 1791, in __getitem__
return self._getitem_array(key)
  File "C:\Users\MVMCJK\Anaconda3\lib\site-packages\pandas\core\frame.py", line 1835, in _getitem_array
indexer = self.ix._convert_to_indexer(key, axis=1)
  File "C:\Users\MVMCJK\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1112, in _convert_to_indexer
raise KeyError('%s not in index' % objarr[mask])
KeyError: "['score1' 'score2' 'score3'] not in index"

尝试按字母顺序对代码进行排序:

Traceback (most recent call last):
  File "C:\Users\MVMCJK\Downloads\Python code\Seperate independent draft of Task 3 (not intergated with Task 1 and 2) draft 3.py", line 74, in <module>
saved_column = df.column_name
  File "C:\Users\MVMCJK\Anaconda3\lib\site-packages\pandas\core\generic.py", line 2150, in __getattr__
(type(self).__name__, name))
AttributeError: 'DataFrame' object has no attribute 'column_name'

最后一部分甚至不能远程工作:由于语法无效,它默认拒绝运行,我必须消除它才能使程序正常工作,当我输入 A3 时它甚至没有给出响应。 我已经尝试用谷歌搜索 KeyError 和 AttributeError ,但我找不到任何与我的问题相关的东西,并使我能够找到进一步的修复。有人知道我的程序有什么好玩的吗?任何帮助将不胜感激。

编辑:更新后仍然无法正常工作的代码:

print("Welcome to the Database sorter. The system works based on the following functions. Choose your class by inputting a letter, and choose the method of sorting the data by inputing a number afterwards. A is for Class A, B is for Class B and C is the Class C.1 is for soritng the data as an average, 2 is for sorting the data in alphabetical order and 3 is for sorting the data from highest to lowest.")
classanddatasorter =''
while classanddatasorter not in ["A1","A2","A3","B1","B2","B3","C1","C2","C3"]:
classanddatasorter = input("You have the following nine options. Input A1 to sort the results of Class A as an average. Input A2 to sort the results of Class A in alphabetical order. Input A3 to sort the results of Class A from highest to lowest. Input B1 to sort the results of Class B as an average. Input B2 to sort the results of Class B in alphabetical order. Input B3 to sort the results of Class B from highest to lowest. Input C1 to sort the results of Class C as an average. Input C2 to sort the results of Class C in alphabetical order. Input C3 to sort the results of Class C from highest to lowest. ")
if classanddatasorter == "A1":
 df = pd.read_csv('classa.csv')
 df['average'] = df[['score1', 'score2', 'score3']].mean(axis=1)

elif classanddatasorter == "A2":
 df = pd.read_csv('classa.csv', index_col='name1')
 saved_column = df.column_name
 name = df.name
 name.sort 

elif classanddatasorter == "A3":
 df = pd.read_csv('classa.csv')
 scores = df[['score1', 'score2', 'score3']].values
 scores.sort(axis=1)


elif classanddatasorter == "B1":
 df = pd.read_csv('classb.csv')
 df['average'] = df[["score1", "score2","score3"]].mean(axis=1)


elif classanddatasorter == "B2":
 df = pd.read_csv('classb.csv',index_col='name1')
 saved_column = df.column_name
 name = df.name

elif classanddatasorter == "B3":
 df = pd.read_csv('classb.csv')
 scores = df[['score1', 'score2', 'score3']].values
 scores.sort(axis=1)

elif classanddatasorter == "C1":
 df = pd.read_csv('classc.csv')
 df['average'] = df[["score1", "score2","score3"]].mean(axis=1)

elif classanddatasorter == "C2":
 df = pd.read_csv('classc.csv',index_col='name1')
 saved_column = df.column_name
 name = df.name
 df = name.sort 

elif classanddatasorter == "C3":
 df = pd.read_csv('classc.csv')
 scores = df[['score1', 'score2', 'score3']].values
 scores.sort(axis=1)

编辑 2:更新了一些 bakkal 的代码示例。

print("Welcome to the Database sorter. The system works based on the following functions. Choose your class by inputting a letter, and choose the method of sorting the data by inputing a number afterwards. A is for Class A, B is for Class B and C is the Class C.1 is for soritng the data as an average, 2 is for sorting the data in alphabetical order and 3 is for sorting the data from highest to lowest.")
classanddatasorter =''
while classanddatasorter not in ["A1","A2","A3","B1","B2","B3","C1","C2","C3"]:
 classanddatasorter = input("You have the following nine options. Input A1 to sort the results of Class A as an average. Input A2 to sort the results of Class A in alphabetical order. Input A3 to sort the results of Class A from highest to lowest. Input B1 to sort the results of Class B as an average. Input B2 to sort the results of Class B in alphabetical order. Input B3 to sort the results of Class B from highest to lowest. Input C1 to sort the results of Class C as an average. Input C2 to sort the results of Class C in alphabetical order. Input C3 to sort the results of Class C from highest to lowest. ")

if classanddatasorter == "A1":
 df = pd.read_csv('classa.csv')
 print('Sorted by name1')
 df.sort('name1')
 print(df)
elif classanddatasorter == "A2":
 df = pd.read_csv('classa.csv')
 print('Sorted by average column')
 df['average'] = df[['score1', 'score2', 'score3']].mean(axis=1)
 print(df)
 print(df[['name1', 'name2', 'average']].sort('average'))
elif classanddatasorter == "A3":
 df = pd.read_csv('classa.csv')
 print('Sorted scores')
 scores = df[['score1', 'score2', 'score3']].values
 scores.sort(axis=1)

 for i in xrange(0, scores.shape[1]):
     column_name = 'rank{}'.format(i)
     df[column_name] = scores[:, i]

print(df[['name1', 'name2', 'rank2', 'rank1', 'rank0']])
elif classanddatasorter == "B1":
 df = pd.read_csv('classb.csv')
 print('Sorted by name1')
 df.sort('name1')
 print(df)
elif classanddatasorter == "B2":
 df = pd.read_csv('classb.csv')
 print('Sorted by average column')
 df['average'] = df[['score1', 'score2', 'score3']].mean(axis=1)
 print(df)
 print(df[['name1', 'name2', 'average']].sort('average'))
elif classanddatasorter == "B3":
 df = pd.read_csv('classb.csv')
 print('Sorted scores')
 scores = df[['score1', 'score2', 'score3']].values
 scores.sort(axis=1)

for i in xrange(0, scores.shape[1]):
    column_name = 'rank{}'.format(i)
    df[column_name] = scores[:, i]

print(df[['name1', 'name2', 'rank2', 'rank1', 'rank0']])
elif classanddatasorter == "C1":
 df = pd.read_csv('classc.csv')
 print('Sorted by name1')
 df.sort('name1')
 print(df)
elif classanddatasorter == "C2":
 df = pd.read_csv('classc.csv')
 print('Sorted by average column')
 df['average'] = df[['score1', 'score2', 'score3']].mean(axis=1)
 print(df)
 print(df[['name1', 'name2', 'average']].sort('average'))
elif classanddatasorter == "C3":
 df = pd.read_csv('classc.csv')
 print('Sorted scores')
 scores = df[['score1', 'score2', 'score3']].values
 scores.sort(axis=1)

 for i in xrange(0, scores.shape[1]):
     column_name = 'rank{}'.format(i)
     df[column_name] = scores[:, i]

print(df[['name1', 'name2', 'rank2', 'rank1', 'rank0']]) 

【问题讨论】:

    标签: python database sorting csv pandas


    【解决方案1】:

    解析与探索

    假设我们有一个这样的 CSV 文件(注意逗号后面的空格,并用逗号分隔,否则您需要使用 CSV 选项来适应您的特定格式)

    scores.csv

    name1,name2,score1,score2,score3
    Atticus,Finch,9,8,10
    Jem,Finch,5,7,6
    Jean Louise,Finch,3,2,4
    

    我们读取了 CSV 文件

    df = pd.read_csv('scores.csv')
    

    现在df 是:

             name1  name2  score1  score2  score3
    0      Atticus  Finch       9       8      10
    1          Jem  Finch       5       7       6
    2  Jean Louise  Finch       3       2       4
    

    df.columns 是:

    Index([u'name1', u'name2', u'score1', u'score2', u'score3'], dtype='object')
    

    如您所见,df 具有 columns 但没有 column_name 属性,因此您的错误如下

    AttributeError: 'DataFrame' 对象没有属性 'column_name'

    排序

    现在让我们进行字母排序

    df.sort('name1')
    

    结果是:

             name1  name2  score1  score2  score3
    0      Atticus  Finch       9       8      10
    2  Jean Louise  Finch       3       2       4
    1          Jem  Finch       5       7       6
    

    你想要平均值,让我们添加一列

    df['average'] = df[['score1', 'score2', 'score3']].mean(axis=1)
    

    df 现在有一个新列可供您排序!

             name1  name2  score1  score2  score3  average
    0      Atticus  Finch       9       8      10        9
    1          Jem  Finch       5       7       6        6
    2  Jean Louise  Finch       3       2       4        3
    

    如果您只想查看average

    df[['name1', 'name2', 'average']].sort('average')
    
    
             name1  name2  average
    0      Atticus  Finch        9
    1          Jem  Finch        6
    2  Jean Louise  Finch        3
    

    你想要的最后一个分数排序有点棘手,因为数据不是整齐/标准化的,但这是一个尝试

    scores = df[['score1', 'score2', 'score3']].values
    

    scores 现在看起来像这样

    array([[ 9,  8, 10],
           [ 5,  7,  6],
           [ 3,  2,  4]])
    

    我们对scores 数组进行排序

    scores.sort(axis=1)
    
    array([[ 8,  9, 10],
           [ 5,  6,  7],
           [ 2,  3,  4]])
    

    这些是您想要的排序分数,所以让我们将它们放入我们的df,我们必须为每个分数列执行此操作,因此我们可以使用scores.shape[1],它是该二维数组中的列数

    for i in xrange(0, scores.shape[1]):
        column_name = 'rank{}'.format(i)
        df[column_name] = scores[:, i]
    

    现在我们的df 看起来像这样

             name1  name2  score1  score2  score3  rank0  rank1  rank2
    0      Atticus  Finch       9       8      10      8      9     10
    1          Jem  Finch       5       7       6      5      6      7
    2  Jean Louise  Finch       3       2       4      2      3      4
    

    并获得您想要的显示

    df[['name1', 'name2', 'rank2', 'rank1', 'rank0']]
    
    
             name1  name2  rank2  rank1  rank0
    0      Atticus  Finch     10      9      8
    1          Jem  Finch      7      6      5
    2  Jean Louise  Finch      4      3      2
    

    整理数据

    您可以阅读this PDF paper了解更多关于整理数据的信息

    基本上很多操作会更容易,例如您的数据应如下所示

    name, test, score
    bob, 1, 10
    bob, 2, 9
    

    而不是

    name, score1, score2
    bob, 10, 9
    

    Python 脚本

    import pandas as pd
    df = pd.read_csv('scores.csv')
    
    print('Original Data')
    print(df)
    
    print('Sorted by name1')
    df.sort('name1')
    print(df)
    
    print('Sorted by average column')
    df['average'] = df[['score1', 'score2', 'score3']].mean(axis=1)
    print(df)
    print(df[['name1', 'name2', 'average']].sort('average'))
    
    print('Sorted scores')
    scores = df[['score1', 'score2', 'score3']].values
    scores.sort(axis=1)
    
    for i in xrange(0, scores.shape[1]):
        column_name = 'rank{}'.format(i)
        df[column_name] = scores[:, i]
    
    print(df[['name1', 'name2', 'rank2', 'rank1', 'rank0']])
    

    除了print(),您还可以将生成的数据帧保存到另一个.csv,例如.to_csv('score_sorted_avg.csv')

    【讨论】:

    • 我很抱歉,但我很难真正利用您的解决方案来使我的代码正常工作。我没有逐字复制它(这可能是它无法运行的原因),但我并不真正理解 In[x] 和 Out[x] 的用法,所以我......做了一些事情?我尝试在重新草稿中使用您的一些示例,但它仍然没有“工作”。您能否详细说明 In[x] 和 Out[x] 的使用以及使用您的技术的一些解释?我将在我的原始帖子中发布我更新的代码以进行解释。我为我的相对无知道歉 - 第一次使用熊猫。 @bakkal
    • 哦,忽略 In/Out 的东西,它们来自一个名为 IPython 的交互式提示,In 是我输入的内容,Out 是我从执行中得到的输出
    • @TheGeezer 你去吧,我把它们拼凑在一起,让你作为 python 脚本运行,假设的 scores.csv 文件在我的答案的顶部
    • @TheGeezer 运行该脚本是否仍有问题?
    • 抱歉延迟 - 有点忙于其他工作试图修补问题。关于程序,我再次稍微调整了它的布局。发生了一些不正常的事情,但我不确定这是缩进不好还是真的不正常,因为当我尝试运行它时,IDLE 只是输出“无效的语法”。我将再次在 desc 中发布更新的更新代码。我真的很感谢你的帮助@bakkal,你是一个绝对的救星。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 2015-03-29
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 2018-03-09
    • 2015-12-01
    相关资源
    最近更新 更多