0
$\begingroup$

This question comes up in my bioinfo class.

I have a csv file containing gene names and the cluster they belong to. I want to run GESA on each individual cluster. So I would like to extract the list of gene names corresponding to each cluster. So I wrote code like this

import pandas as pd
gene_list = pd.read_csv('marker_genes.csv')
for i in range(12):
    "cluster_"+str(i) = gene_list.gene[gene_list.cluster==i]

I know this raises syntax error, so what is the correct way of doing it. In the end, I would want cluster_0 to cluster_12 each being a list of gene names.

$\endgroup$
3
  • 1
    $\begingroup$ You're looking for the groupby() function pandas.pydata.org/pandas-docs/stable/reference/api/… $\endgroup$
    – Devon Ryan
    Apr 11 '20 at 8:46
  • 1
    $\begingroup$ Groupby is probably right, not always easy to get the object to spit out the values. Difficult without knowing the table format $\endgroup$
    – M__
    Apr 11 '20 at 13:01
  • $\begingroup$ Reshaping via melt is another possible way in or pivoting might work. There's probably lots of solutions. The pd.read_csv is a neat part of pandas, however you rarely use loops, only when you are stuck and its a different syntax. $\endgroup$
    – M__
    Apr 11 '20 at 13:12
1
$\begingroup$

cluster_0 to cluster_12 are just strings. they cannot be the names of arrays or matrices. Strings can only be used in print statements and string processing statements.

The correct way to define an array or matrix is as follows: call the arrays as: cluster[0] to cluster[12]

then, assign:

  for i in range(12):
        cluster[i] = gene_list.gene[gene_list.cluster==i]

then whenever you need to print the names of these arrays, you use: "cluster_"+str(i)

$\endgroup$
1
  • $\begingroup$ Okay .... yeah, this is better. There is an issue with the "cluster" dictionary (??), so I still think it will throw an error, but it is a definite improvement. The pandas command that is the formal solution is "iterrows" for this style of loop. – its a fun question. $\endgroup$
    – M__
    Apr 11 '20 at 22:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.