我有一个看起来像这样的熊猫数据框:
Name Age
0 tom 10
1 nick 15
2 juli 14
我正在尝试遍历每个名称->连接到mysql数据库->将名称与数据库中的列匹配->获取名称的ID->并替换ID为名称
在上述数据框中。所需的输出如下:
Name Age
0 1 10
1 2 15
2 4 14
以下是我尝试过的代码:
import pandas as pd
import MySQLdb
from sqlalchemy import create_engine
engine = create_engine("mysql+mysqldb://root:Abc@123def@localhost/aivu")
data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])
print(df)
for index, rows in df.iterrows():
cquery="select id from students where studentsName="+'"' + rows['Name'] + '"'
sid = pd.read_sql(cquery, con=engine)
df['Name'] = sid['id'].iloc[0]
print(df[['Name','Age')
上面的代码显示以下输出:
Name Age
0 1 10
1 1 15
2 1 14
Name Age
0 2 10
1 2 15
2 2 14
Name Age
0 4 10
1 4 15
2 4 14
我知道,它会为每个匹配的名称遍历整个表并打印出来。您如何只将值替换一次。
您可以通过以下方式进行这种操作,请按照评论并随时提出问题:
import pandas as pd
# create frame
x = pd.DataFrame(
{
"name": ["A", "B", "C"],
"age": [1, 2, 3]
}
)
# create some kind of db
mock_database = {"A": 10, "B": 20, "C": 30}
x["id"] = None # add empty column
print(x)
# change values in the new column
for i in range(len(x["name"])):
x["id"][i] = mock_database.get(x["name"][i])
print("*" * 100)
print(x)
一种好的方法是:
import pandas as pd
import MySQLdb
from sqlalchemy import create_engine
engine = create_engine("mysql+mysqldb://root:Abc@123def@localhost/aivu")
data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])
print(df)
name_ids = []
for student_name in df['Name']:
cquery="select id from students where studentsName='{}'".format(student_name)
sid = pd.read_sql(cquery, con=engine)
name_ids.append(sid if sid is not None else None )
# DEBUGED WITH name_ids = [1,2,3]
df['Name'] = name_ids
print(df)
我检查了一个ID列表示例,它可以正常工作,我想查询格式是否正确也可以。在性能方面,我认为没有更好的解决方案,因为您将不得不进行很多查询(每个学生一个),但是可能有一些方法可以用更少的查询获取所有id。