【发布时间】:2020-12-28 20:12:56
【问题描述】:
import pymysql
import pandas as pd
import numpy
conn = pymysql.connect(host="localhost",port=3306,db="school",user="root",password="@mit123")
print("Connection established sucessfully")
cursor = conn.cursor()
sql = "SELECT * FROM records"
cursor.execute(sql)
result = cursor.fetchall()
data= result
df = pd.DataFrame(data)
df1=df.T
print(df)
print(df1)
df2 = pd.DataFrame(df1,index=["id","name","rollno.","city"])
print(df2)
以下是输出。什么可能导致问题?我不能将一个数据帧转置为另一个数据帧吗?
Connection established sucessfully
0 1 2 3 4
0 1 amit 1 92 jorhat
1 2 subham 2 93 jorhat
2 3 ram 3 89 surat
3 4 anil 4 91 delhi
4 5 abdul 5 81 bhopal
5 6 joseph 6 90 sikkim
6 7 Ben 7 94 indore
7 8 tom 8 99 goa
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8
1 amit subham ram anil abdul joseph Ben tom
2 1 2 3 4 5 6 7 8
3 92 93 89 91 81 90 94 99
4 jorhat jorhat surat delhi bhopal sikkim indore goa
0 1 2 3 4 5 6 7
id NaN NaN NaN NaN NaN NaN NaN NaN
name NaN NaN NaN NaN NaN NaN NaN NaN
rollno. NaN NaN NaN NaN NaN NaN NaN NaN
city NaN NaN NaN NaN NaN NaN NaN NaN
Process finished with exit code 0
这是我的 sql 表:
当我在数据框中使用索引时,它会显示形状错误:
Shape of passed values is (5, 8), indices imply (4, 8)
【问题讨论】:
-
如果您将数据框创建为
df=pd.read_sql(sql=sql,con=conn)会发生什么? -
原因可能是通过传递获取结果而不是通过 read_sql 生成数据帧时没有列名吗?
-
请不要全部大写。看起来你在大喊大叫。
标签: python pandas dataframe nan transpose