我有一個大型凌亂的 SQL 資料庫,我已經開始清理它,我需要檢查表中是否存在用戶 ID,最好是在一個視圖中。我從左連接開始,列出所有用戶 ID,但在我的情況下,5 個以上的表的性能確實很差。
所以我決定使用 python 并獲取串列中的 ID,并將它們連接到一個 pandas 資料框中。我唯一的問題是我無法真正弄清楚如何使用 python 進行左連接,就像我使用 SQL 一樣。
我有 10 多個用戶 ID 串列,理想情況下,我需要一個資料框,其中索引是所有用戶 ID,列代表指示是否可以找到用戶 ID 的表(是/否)。
這是我設法做的:
users = pd.DataFrame(users)
table1 = pd.DataFrame(table1)
users = users.merge(table, how='left', indicator='table1')
然后我需要遍歷所有串列并將它們與用戶合并,重命名指標文本left_only = 'No' both = 'Yes'和reindex()最終表格。
關于如何以更優雅的方式執行此操作的任何建議?
uj5u.com熱心網友回復:
好的,所以我想通了。我想要的資料集看起來像這樣:
users table1 table2 table3
----- ------ ------ ------
1 True None None
2 True True None
3 None None True
4 None None None
5 True True True
沒有必要使用 pandas,最好使用純 python 來合并列。
users = [1, 2, 3, 4, 5]
tables = [table1, table2, table3]
data = {
'users': users
}
for table in tables:
column = []
for user in users:
if user in table:
column.append(True)
else:
column.append(None)
data[table] = column
然后將其放入資料框中
df = pd.DataFrame.from_dict(data)
df.sort_values('users').reset_index(drop=True)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/536564.html
上一篇:如何加入fillnullbypreviousvalue
下一篇:如何連接前綴相等的表?
