【问题标题】:I have a csv file, i am using pandas to import the csv. i need to read through each row and only print if my value is 1 for that row我有一个 csv 文件,我正在使用 pandas 导入 csv。我需要通读每一行,并且仅在我的值为该行的 1 时打印
【发布时间】:2020-09-07 14:30:22
【问题描述】:

例如:

我的 csv:

我的学生选修了不同的课程,我想知道有多少学生选修了哪门课程。

    stud1 stud2 stud3 stud4 stud5 
c1    1     0     0     0     0  
c2    0     1     0     0     0
c3    0     0     1     1     0
c4    1     0     0     0     1 
c5    0     0     0     0     1

我希望输出为:

course [1,1,2,2,1]

enter image description here

【问题讨论】:

    标签: python pandas csv spyder


    【解决方案1】:

    只需修改这个例子。

    dataframe = pandas.read_csv("mycsv")
    number = 0
    for index in dataframe.indexs:
        for  i in range(len(dataframe.loc[index].values)):
            if(dataframe.loc[index].values[i] =='fox'):
                number += 1
    print(number)
    

    【讨论】:

      【解决方案2】:

      你可以使用 lambda 来解决这个问题。

      df = pd.DataFrame([[1,0,0,0,0],[0,1,0,0,0],[0,0,1,1,0],[1,0,0,0,1],[0,0,0,0,1]])
      df.apply(lambda x: x.sum(), axis = 1).values
      

      [输出]:

      array([1, 1, 2, 2, 1], dtype=int64)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-24
        • 2021-07-15
        相关资源
        最近更新 更多