![](/img/trans.png)
[英]Is there a way to combine multiple excel-sheets from multiple excel-files with the same format?
[英]Which is an efficient way for checking values of multiple rows with the same keyvalue in two different excel-files/dataframes?
我有兩個Excel文件。 兩者都包含有關相同數據對象的信息。 數據對象由類型為str
的對象編號(列ON
)標識。
例:
Table 1 Table 2
ON colA colB colToUpdate ON colImportant
1.2.3 abc 123 1.2.3 inf
2.9.6 ert 987 1.2.3 mat
3.5.0 nms 021 2.9.6 mat
2.9.6 tr
2.9.6 ch
3.5.0 tr
和
myValues={inf, ch}
任務:
我需要檢查表2中的colImportant
值之一是否在myValues
並且該數據對象(具有相同對象號的行)需要在df1
colToUpdate
中獲取值“ Ok”。
期望:
new Table 1
ON colA colB colToUpdate
1.2.3 abc 123 Ok
2.9.6 ert 987 Ok
3.5.0 nms 021 NaN
我想到了這兩個在一個單獨的數據幀(表1 IND保存df1
和表2中df2
)始終搜索相同的對象號在df2
在更新下一列時df1
。 但這總是會搜索整個df2
( df2
有30000個數據對象,這意味着df1
有30000行。在df2
,有75000行,因為一個數據對象可以與colImportant
另一個值多次存儲,如您在上面看到的)。
另一個想法是在df1
中創建一個tempCol
在其中我將所有來自colImportant
的值放在df2
並使用分隔符,
(但是,我需要將多行合並到df2
然后將dfs合並為'ON'
) 。 然后,當我想通過某些條件更新df1
的行時,我必須檢查拆分后的值。 完成后,我可以刪除tempCol
。 看起來應該像這樣:
Table 1
ON colA colB colToUpdate tempCol
1.2.3 abc 123 inf,mat
2.9.6 ert 987 mat,tr,ch
3.5.0 nms 021 inf
這是我的方法:
tmp_df = df2.groupby('ON').colImportant.apply(lambda x: 'OK' if (~x.isin(myValues)).any()
else np.nan)
df1=df1.merge(tmp_df.reset_index()[['colImportant']],
left_on=df1.ON,
right_on=tmp_df.index).drop('key_0', axis=1)
輸出:
+----+-------+--------+----------------+
| | ON | colA | colImportant |
|----+-------+--------+----------------|
| 0 | 1.2.3 | abc | OK |
| 1 | 2.9.6 | ert | OK |
| 2 | 3.5.0 | nms | nan |
+----+-------+--------+----------------+
不完美,但我認為您可以解決。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.