簡體   English   中英

比較來自不同數據幀的多列具有相同長度 Pandas

[英]Compare multiple columns from differemt dataframes with same length Pandas

我有四個具有以下結構的數據框:

df1
   max_proba    chosen_class
0   0.8            class_A
1   0.92           class_B
2   0.82           class_B
3   0.74           class_B
4   0.58           class_A

df2
   max_proba    chosen_class
0   0.6            class_C
1   0.62           class_D
2   0.87           class_D
3   0.94           class_C
4   0.62           class_D

# ... and same for df3 and df4 only chosen class values and probabilities that change!

我想比較所有 4 個數據幀之間的列“max_proba”,並在選擇 class 的情況下保持最大值。

(例如:一個樣本,如果 df1 max_proba = 0,23,df2 max_proba = 0,86, df3 max_proba = 0,56, df4 max_proba = 76 ==> 在這里我只想要選擇的 class 概率最高為 0,86可以是class_E(例如))

如果我沒聽錯,你想逐行比較它們。

您應該將它們加入一個數據框:

df = df1.append(df2)

然后使用先前數據幀中的行數創建一個新列“索引”,並在此 dataframe 中創建一個具有行數的列“level_0”:

df = df.reset_index()
df = df.reset_index()

並找到每個索引最大的行的索引:

indexes = df.groupby('index').apply(lambda x: x.max_proba == max(x['max_proba'])).reset_index()

最后,select 行與我們的索引的大數據幀中的 max_proba 最大:

result = df.loc[indexes[indexes.max_proba].level_1.values]

output 將類似於:

level_0 index   max_proba   chosen_class
0   0   0   0.80    class_A
1   1   1   0.92    class_B
7   7   2   0.87    class_D
8   8   3   0.94    class_C
9   9   4   0.62    class_D

您可以使用 function drop刪除額外的列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM