[英]Using Merge on a column and Index in Pandas
我有兩個單獨的數據框,它們共享一個項目編號。 在type_df
,項目編號是索引。 在time_df
,項目編號是一列。 我想計算type_df
中Project Type
為2
的行數。 我正在嘗試使用pandas.merge()
來做到這一點。 使用兩列時效果很好,但不能使用索引。 我不確定如何引用索引,以及merge
是否是正確的方法。
import pandas as pd
type_df = pd.DataFrame(data = [['Type 1'], ['Type 2']],
columns=['Project Type'],
index=['Project2', 'Project1'])
time_df = pd.DataFrame(data = [['Project1', 13], ['Project1', 12],
['Project2', 41]],
columns=['Project', 'Time'])
merged = pd.merge(time_df,type_df, on=[index,'Project'])
print merged[merged['Project Type'] == 'Type 2']['Project Type'].count()
錯誤:
名稱“索引”未定義。
期望輸出:
2
如果要在合並中使用索引,則必須指定left_index=True
或right_index=True
,然后使用left_on
或right_on
。 對你來說,它應該是這樣的:
merged = pd.merge(type_df, time_df, left_index=True, right_on='Project')
另一種解決方案是使用DataFrame.join
:
df3 = type_df.join(time_df, on='Project')
對於版本pandas 0.23.0+
的on
、 left_on
和right_on
參數現在可以引用列名或索引級別名稱:
left_index = pd.Index(['K0', 'K0', 'K1', 'K2'], name='key1')
left = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3'],
'key2': ['K0', 'K1', 'K0', 'K1']},
index=left_index)
right_index = pd.Index(['K0', 'K1', 'K2', 'K2'], name='key1')
right = pd.DataFrame({'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3'],
'key2': ['K0', 'K0', 'K0', 'K1']},
index=right_index)
print (left)
A B key2
key1
K0 A0 B0 K0
K0 A1 B1 K1
K1 A2 B2 K0
K2 A3 B3 K1
print (right)
C D key2
key1
K0 C0 D0 K0
K1 C1 D1 K0
K2 C2 D2 K0
K2 C3 D3 K1
df = left.merge(right, on=['key1', 'key2'])
print (df)
A B key2 C D
key1
K0 A0 B0 K0 C0 D0
K1 A2 B2 K0 C1 D1
K2 A3 B3 K1 C3 D3
您必須在每個數據框中具有相同的列才能合並。
在這種情況下,只需為type_df
創建一個“項目”列,然后合並:
type_df['Project'] = type_df.index.values
merged = pd.merge(time_df,type_df, on='Project', how='inner')
merged
# Project Time Project Type
#0 Project1 13 Type 2
#1 Project1 12 Type 2
#2 Project2 41 Type 1
print merged[merged['Project Type'] == 'Type 2']['Project Type'].count()
2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.