![](/img/trans.png)
[英]Replacing values in data frame with another data frame based on one of the columns
[英]How to add values in a pandas data frame based on values of two columns of one of the data frame merged
我需要根據作為我的對照的另一個測試來計算測試的靈敏度和特異性。 為此,我需要合並三個數據框。
第一個連接位於包含所有案例的列與包含控制測試結果的另一列之間。 (我知道如何做到這一點,但我展示了上一步,讓您了解我最后需要做什么)。
第一個數據框:
data = [['ch1.1234578C>T'], ['ch2.123459G>A'], ['ch3.234569A>T'], ['chX.246890A>G']]
comparison = pd.DataFrame(data, columns = ['All_common_variants_ID'])
comparison
All_common_variants_ID
1 ch1.1234578C>t
2 ch2.123459G>A
3 ch3.234569A>T
4 chX.246890A>G
第二個數據框:
data = [['ch1.1234578C>T'], ['ch2.123459G>A']]
control = pd.DataFrame(data, columns = ['Sample_ID'])
control
Sample_ID
1 ch1.1234578C>T
2 ch2.123459G>A
我已將這兩個數據框與此代碼合並:
comparative = comparison.merge(control[['Sample_ID']],left_on='All_common_variants_ID',right_on='Sample_ID',how='outer').fillna('Real negative')
comparative = comparative.rename(columns={'Sample_ID': 'CONTROL'})
comparative
All_common_variants_ID CONTROL
1 ch1.1234578C>T ch1.1234578C>T
2 ch2.123459G>A ch2.123459G>A
3 ch3.234569A>T Real negative
4 chX.246890A>G Real negative
現在是我遇到問題的地方。
我需要在條件下將第三個數據框(測試)與comparative
數據框的第一列和第二列連接起來。
條件是:
根據提供的樣本,這將是預期的結果。
All_common_variants_ID CONTROL Test
1 ch1.1234578C>T ch1.1234578C>T True-positive # ch1.1234578C>T match with the second column
2 ch2.123459G>A ch2.123459G>A False-negative # ch2.123459G>A is not in my test column
3 ch3.234569A>T Real negative False-positive # ch3.234569A>T match with first column but second column is real negative
4 chX.246890A>G Real negative True-negative # chX.246890A>G is not in my test column and is not in the control column.
一些評論:
使用np.select
# Setup test dataframe
data = [['ch1.1234578C>T'], ['ch3.234569A>T']]
test = pd.DataFrame(data, columns=['Test'])
# Build variables to np.select
condlist = [comparative['CONTROL'].isin(test['Test']),
~comparative['CONTROL'].isin(test['Test'])
& comparative['CONTROL'].ne('Real negative'),
comparative['All_common_variants_ID'].isin(test['Test'])
& comparative['CONTROL'].eq('Real negative')]
choicelist = ['True-positive', 'False-negative', 'False-positive']
default = 'True-negative'
# Create new column
comparative['Test'] = np.select(condlist, choicelist, default)
輸出:
>>> comparative
All_common_variants_ID CONTROL Test
0 ch1.1234578C>T ch1.1234578C>T True-positive
1 ch2.123459G>A ch2.123459G>A False-negative
2 ch3.234569A>T Real negative False-positive
3 chX.246890A>G Real negative True-negative
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.