sqlite 在Python上将相同的行合并到一个数据库中

dz6r00yl  于 2023-04-21  发布在  SQLite
关注(0)|答案(1)|浏览(156)

我有数据库,我想合并成1行相同的行
示例:

Game   |   Creator  |   Year
________________________________
aaa    |   zzz      |   2002
________________________________
bbb    |   xxx      |   2001
________________________________
aaa    |   zzz      |   2000
________________________________
bbb    |   xxx      |   3001

我想得到:

Game   |   Creator  |   Year    |
________________________________|
aaa    |   zzz      |   2002
       |            |___________|
       |            |   2000    | 
________________________________|
bbb    |   xxx      |   2001    |
       |            |___________|  
       |            |   3001    |
________________________________|

P.S.不要合并“年份”列

d5vmydt9

d5vmydt91#

由于问题不清楚,我假设您正在将数据库导入python,然后执行操作,我建议使用sqlite3执行这些操作

import pandas as pd
import sqlite3

# connect to the database
data = sqlite3.connect('database_name.db')

# execute the SQL query and load the results into a pandas df
df = pd.read_sql_query("SELECT Game, Creator, GROUP_CONCAT(Year, ', ') AS Years FROM table_name GROUP BY Game, Creator;", data)

print(df)

相关问题