![](/img/trans.png)
[英]How to divide one column by another where one dataframe's column value corresponds to another dataframe's column's value in Python Pandas?
[英]python pandas: Check if dataframe's column value is in another dataframe's column, then count and list it
在這里學習Python,對此有任何幫助非常感謝。 我有一個由兩部分組成的問題,盡管我已經為第一部分創建了一個解決方案,但必須有更多的pythonic方法來實現這個目標。 第二部分,不太確定如何進行。
我在兩個獨立的數據幀中有唯一ID列。 我想計算df_2的uid列中uid列中uid出現的次數,然后將該uid添加到列表中(如果兩者都是)。 以下代碼示例適用於我,但我擔心某處存在問題,並且必須有更好的方法。
data = {'uid':['uid1', 'uid2', 'uid3', 'uid4'], 'value': [1, 2, 3, 4]}
df = pd.DataFrame(data)
data1 = {'uid':['uid4', 'uid2', 'uid5'], 'value1': ["", 5, 6]}
df1 = pd.DataFrame(data1)
count_val_in_both_df = 0
list_val_in_both_df = []
for x in range(len(df1.iloc[:, 0])) :
if df1.iloc[x, 0] in df.iloc[:, 0].values :
count_val_in_both_df += 1
list_val_in_both_df.append(df1.iloc[x, 0])
print('count = ' + str(count_val_in_both_df))
print(list_val_in_both_df)
哪個輸出:
df
uid value
0 uid1 1
1 uid2 2
2 uid3 3
3 uid4 4
df1
uid value1
0 uid4
1 uid2 5
2 uid5 6
count = 2
['uid4', 'uid2']
第二部分是在df中為df1中的值創建一個列,並添加df1中的值。 我很遺憾這部分,但想要這樣的結果:
{ uid value value1
0 uid1 1
1 uid2 2 5
2 uid3 3
3 uid4 4 }
您可以使用合並
df.merge(df1, on = 'uid', how = 'left').fillna('')
uid value value1
0 uid1 1
1 uid2 2 5
2 uid3 3
3 uid4 4
對於問題的第一部分,您可以使用交集
list_val_in_both_df = list(set(df.uid).intersection(set(df1.uid)))
你得到
['uid2', 'uid4']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.