This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Python3: How to split the tuple generated by the .groupby function in pandas

My Code

data = pd.read_csv('input_file', header = None, delimiter="\t", names = ['chr', 'sTSS', 'eTSS', 'gene', 'clust1', 'clust2'])

dup_clust2 = data.groupby('clust2').filter(lambda x: len(x) > 1)

for element in dup_clust2.groupby('clust2'):
    print(element)

Input: <tab separated="" file="">

chr2   166760255  166760255  Cse1l_tss10    52    5426
chr2   166760282  166760282  Cse1l_tss9    52    5426
chr2   166885599  166886548  IRF8   150.18    5431
chr2   166885925  166885925  Znfx1_tss1    52    5433

Output: <tab separated="" file="">

(5426,    chr    sTSS    eTSS    gene    clust1    clust2
0    chr2    166760255    166760255    Cse1l_tss10    52.0    5426
1    chr2    166760282    166760282    Cse1l_tss9    52.0    5426)

Required Output:<tab separated="" file=""> split tuple in two lines

(0    chr2    166760255    166760255    Cse1l_tss10    52.0    5426)
(1    chr2    166760282    166760282    Cse1l_tss9    52.0    5426)
python3

Hello tinkuhim007!

We believe that this post does not fit the main topic of this site.

Thread now has answers, but was not a bioinformatics question in the first place so should have been closed at the time.

For this reason we have closed your question. This allows us to keep the site focused on the topics that the community can help with.

If you disagree please tell us why in a reply below, we'll be happy to talk about it.

Cheers!

2 answers

Any particular reason to keep tabs?

import pandas as pd
data = pd.read_csv("file.txt", header = None, delimiter="\t", names = ['chr', 'sTSS', 'eTSS', 'gene', 'clust1', 'clust2'])
dup_clust2 = data.groupby('clust2').filter(lambda x: len(x) > 1).to_records().tolist()
for t in dup_clust2:
        print(t)
        #print with tabs
        #out="\t".join(map(str,t))
        #print(out)

The output of .groupby() function is tuple but the values of such tuple are dataframe, so we have to access their values using keys. I have just tried one solution using the same approach, it might help you.

import pandas as pd

data = pd.read_csv('input.txt', header = None, delimiter="\t", names = ['chr', 'sTSS', 'eTSS', 'gene', 'clust1', 'clust2'])
dup_clust2 = data.groupby('clust2').filter(lambda x: len(x) > 1)

userDict = {}

for element in dup_clust2.groupby('clust2'):
    for key in element[1]:
        index = 0
        for i in element[1][key]:
            if(not index in userDict):
                userDict[index] = []
            userDict[index].append(i)
            index = index + 1

for key in userDict:
    print(userDict[key])

Log in to answer this question.