如何将索引列转换为数字?

时间:2017-08-13 06:46:49

标签: python pandas

我有一个数据框,其索引行是字符串数据类型。我希望它是数字和排序:

  col1 col2
1  25   33
3  35  544
2  24   52

预期:

  col1 col2
1  25   33
2  24   52
3  35   544

2 个答案:

答案 0 :(得分:3)

首先,使用pd.to_numeric进行转换和分配。

df.index = pd.to_numeric(df.index, errors='coerce')

要按索引对DataFrame进行排序,请调用df.sort_index

df.sort_index()

   col1  col2
1    25    33
2    24    52
3    35   544

如果您想进行就地操作,可以为第二个命令指定inplace=True,或者可以将其传递给管道。

答案 1 :(得分:1)

您可以使用import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Time; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class MySQLDatabaseDemo { Connection conn = null; PreparedStatement preparedStatement = null; public static Connection getConnection() throws Exception { String driver = "org.gjt.mm.mysql.Driver"; String url = "jdbc:mysql://localhost/databaseName"; String username = "root"; String password = "root"; Class.forName(driver); Connection conn = DriverManager.getConnection(url, username, password); return conn; } /** * @param args [0] = value of "id" * [1] = value of "name" * [2] = value of "time_from" */ public void insertRowWithTimeDatatype(String[] args) { String query = "insert into my_table (id, name, timefrom) " + "values (?, ?, ?)"; DateFormat sdf = new SimpleDateFormat("hh:mm:ss"); Date date = sdf.parse(args[2]); Time time = new Time(date.getTime()); try { conn = getConnection(); // getConnection() is YOUR method preparedStatement = conn.prepareStatement(query); preparedStatement.setInt(1, Integer.parseInt(args[0])); preparedStatement.setString(2, args[1]); preparedStatement.setTime(3, time); // Execute statement and return the number of rows affected int rowCount = preparedStatement.executeUpdate(); System.out.println("Number of rows affected: " + rowCount); } finally { preparedStatement.close(); conn.close(); } } } astype

sort_index

,使用In [833]: df.index Out[833]: Index([u'1', u'3', u'2'], dtype='object') In [834]: df.index = df.index.astype(int) In [837]: df = df.sort_index() In [838]: df Out[838]: col1 col2 1 25 33 2 24 52 3 35 544 In [839]: df.index Out[839]: Int64Index([1, 2, 3], dtype='int64')

的单个班轮
set_index