![](/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.