簡體   English   中英

保持行具有特定列的最大值

[英]Keep rows with max value of a specific column

我是Python的新手,我想做以下事情。 我有一個csv文件(input.csv),其中包含標題行和4列。 該csv文件的一部分如下所示:

gene-name p-value stepup(p-value) fold-change
IFIT1 6.79175E-005 0.0874312 96.0464
IFITM1 0.00304362 0.290752 86.3192
IFIT1 0.000439152 0.145488 81.499
IFIT3 5.87135E-005 0.0838258 77.1737
RSAD2 6.7615E-006 0.0685623 141.898
RSAD2 3.98875E-005 0.0760279 136.772
IFITM1  0.00176673 0.230063 72.0445

我只想保留倍數變化最高的行,而刪除所有其他具有相同基因名稱且倍數變化較低的行。 例如,在這種情況下,我需要以下格式的csv輸出文件:

gene-name p-value stepup(p-value) fold-change
IFIT1 6.79175E-005 0.0874312 96.0464
IFITM1 0.00304362 0.290752 86.3192
RSAD2 6.7615E-006 0.0685623 141.898   
IFIT3 5.87135E-005 0.0838258 77.1737

如果您為我提供了解決此問題的方法,我將不勝感激。
非常感謝你。

愚蠢的解決方案:遍歷文件中的每一行,進行手動比較。 假設:

  • 每列由一個空格分隔
  • 結果行的數量預計將適合內存,因為我們必須完成整個搜索並進行比較,然后再將結果刷新到文件中
  • 沒有預排序,因此縮放比例(速度)很差,因為它會在每個輸入行上執行完整的結果列表。
  • 如果某個基因后來具有相同的倍數變化,則您希望保留該基因的第一行。

::

fi = open('inputfile.csv','r') # read

header = fi.readline() 
# capture the header line ("gene-name p-value stepup(p-value) fold-change")    

out_a = [] # we will store the results in here

for line in fi: # we can read a line this way too
    temp_a = line.strip('\r\n').split(' ') 
    # strip the newlines, split the line into an array

    try:
        pos = [gene[0] for gene in out_a].index(temp_a[0])
        # try to see if the gene is already been seen before
        # [0] is the first column (gene-name)
        # return the position in out_a where the existing gene is
    except ValueError: # python throws this if a value is not found
        out_a.append(temp_a)
        # add it to the list initially
    else: # we found an existing gene
        if float(temp_a[3]) > float(out_a[pos][3]):
            # new line has higher fold-change (column 4)
            out_a[pos] = temp_a
            # so we replace

fi.close() # we're done with our input file
fo = open('outfile.csv','w') # prepare to write to output
fo.write(header) # don't forget about our header
for result in out_a:
    # iterate through out_a and write each line to fo
    fo.write(' '.join(result) + '\n')
    # result is a list [XXXX,...,1234]
    # we ' '.join(result) to turn it back into a line
    # don't forget the '\n' which makes each result on a line

fo.close()

這樣的一個優點是它保留了輸入文件中基因的第一個遇到的順序。

嘗試使用熊貓:

import pandas as pd

df = pd.read_csv('YOUR_PATH_HERE')

print(df.loc[(df['gene-name'] != df.loc[(df['fold-change'] == df['fold-change'].max())]['gene-name'].tolist()[0])])

代碼很長,因為我選擇在一行中執行此操作,但是代碼正在執行此操作。 我搶gene-name最高的fold-change ,然后我用的!=操作員說,“搶了我一切,其中gene-name是不一樣的gene-name ,我們只是做了計算。

細分:

# gets the max value in fold-change
max_value = df['fold-change'].max()

# gets the gene name of that max value
gene_name_max = df.loc[df['fold-change'] == max_value]['gene-name']

# reassigning so you see the progression of grabbing the name
gene_name_max = gene_name_max.values[0]

# the final output
df.loc[(df['gene-name'] != gene_name_max)]

輸出:

gene-name   p-value stepup(p-value) fold-change
0   IFIT1   0.000068    0.087431    96.0464
1   IFITM1  0.003044    0.290752    86.3192
2   IFIT1   0.000439    0.145488    81.4990
3   IFIT3   0.000059    0.083826    77.1737
6   IFITM1  0.001767    0.230063    72.0445

編輯:

要獲得預期的輸出,請使用groupby

import pandas as pd

df = pd.read_csv('YOUR_PATH_HERE')
df.groupby(['gene-name'], sort=False)['fold-change'].max()

# output below
gene-name
IFIT1      96.0464
IFITM1     86.3192
IFIT3      77.1737
RSAD2     141.8980

暫無
暫無

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

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