如何在Python中将“矩阵”转换为“数据框”?

时间:2019-07-17 09:35:30

标签: python dataframe

我通过以下代码使用“ Vectorizer”构建了特征矩阵

Ok I got the answer thanks...
We have to use do....while instead of just while....it was 
just skipping single data each time.....bcoz while is not 
going to check second time if data is available or not....below is 
the code...
.
  if (resultSet.next()) {
    do {
          Attn_Type = resultSet.getString(1);
          String Time = resultSet.getString(2);
          String Reason = resultSet.getString(3);

   if (Attn_Type.equals("I")) {
       String Attn_Type_In = "In";
       String Attn_Type_Out = null;

     StringBuilder stringBuilder = new StringBuilder("" + i);
     String date_no = stringBuilder.toString();

      myOptions.add(new Attendance_Data(Attn_Type_In, 
      weekDate, Reason, i, date_no, month_name, Time));

    } else {
     String Attn_Type_Out = "Out";
     String Attn_Type_In = null;
     StringBuilder stringBuilder = new StringBuilder("" + i);
     String date_no = stringBuilder.toString();

         myOptions.add(new Attendance_Data(Attn_Type_Out, 
         weekDate, Reason, i, date_no, month_name, Time));
        }
      } while (resultSet.next());
  } else {
     Attn_Type = "Absent";
     String out = null;
     String Reason = null;
     String Time = null;
     StringBuilder stringBuilder = new StringBuilder("" + i);
     String date_no = stringBuilder.toString();             

     myOptions.add(new Attendance_Data(Attn_Type, weekDate, 
     Reason, i, date_no, month_name, Time));
      }
    }
  }

然后我在代码下申请将矩阵转换为数据框。

matrix = vectorizer.fit_transform(list)

但是我遇到了一个错误:

df = pd.DataFrame(matrix)

如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

您必须将肯定是稀疏矩阵的矩阵转换为密集矩阵。

matrix = matrix.todense()

答案 1 :(得分:0)

您可以这样尝试:

matrix = vectorizer.fit_transform(list)
df = pd.DataFrame(matrix .todense())
# OR
df = pd.DataFrame(matrix .todense(),columns=vectorizer.get_feature_names())

适合您的