Pandas:根据字典更改数据框值并删除不匹配的行

时间:2014-09-16 01:56:11

标签: python dictionary replace pandas

我有一个pandas数据框,其中一行包含以下格式列出的染色体:“chr1”,“chr2”......

我有一个字典可以将这些值转换为整数 - 例如:

HashTable = {"chr1" : 1, "chr2" : 2, "chr3" : 3, "chr4" : 4, "chr5" : 5, "chr6" : 6, "chr7" : 7, "chr8" : 8, "chr9" : 9, "chr10" : 10, "chr11" : 11, "chr12" : 12, "chr13" : 13, "chr14" : 14, "chr15" : 15, "chr16" : 16, "chr17" : 17, "chr18" : 18, "chr19" : 19, "chrX" : 20, "chrY" : 21, "chrM" : 22, 'chrMT': 23}

我想将数据帧“Chrom”列中的染色体转换为整数值。字典中还没有找到一些我想从数据框中删除的染色体。有一种简单的方法可以做到这一点吗?

1 个答案:

答案 0 :(得分:4)

您可以使用isin过滤有效行,然后使用replace替换值:

import pandas as pd
HashTable = {"chr1" : 1, "chr2" : 2, "chr3" : 3, "chr4" : 4, "chr5" : 5, "chr6" : 6, "chr7" : 7, "chr8" : 8, "chr9" : 9, "chr10" : 10, "chr11" : 11, "chr12" : 12, "chr13" : 13, "chr14" : 14, "chr15" : 15, "chr16" : 16, "chr17" : 17, "chr18" : 18, "chr19" : 19, "chrX" : 20, "chrY" : 21, "chrM" : 22, 'chrMT': 23}
# A dummy DataFrame with all the valid chromosomes and one unknown chromosome
df = pd.DataFrame({"Chrom": HashTable.keys() + ["unknown_chr"]})
# Filter for valid rows
df = df[df["Chrom"].isin(HashTable.keys())]
# Replace the values according to dict
df["Chrom"].replace(HashTable, inplace=True)
print df

输入(上面的虚拟df):

          Chrom
0         chrMT
1          chrY
2          chrX
3         chr13
4         chr12
5         chr11
6         chr10
7         chr17
8         chr16
9         chr15
10        chr14
11        chr19
12        chr18
13         chrM
14         chr7
15         chr6
16         chr5
17         chr4
18         chr3
19         chr2
20         chr1
21         chr9
22         chr8
23  unknown_chr

输出DataFrame:

   Chrom
0     23
1     21
2     20
3     13
4     12
5     11
6     10
7     17
8     16
9     15
10    14
11    19
12    18
13    22
14     7
15     6
16     5
17     4
18     3
19     2
20     1
21     9
22     8

如果结果值都是整数,则更改上面的replace行以强制执行正确的dtype

df["Chrom"] = df["Chrom"].replace(HashTable).astype(int)