基于多个列值输出多个文件

2024-06-13 18:45:42 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题跟在我前面的问题output multiple files based on column value python pandas后面 但这次我想更进一步。你知道吗

所以这次我有一个小样本数据集:

import pandas as pd

df = {'ID': ['H900','H901','H902','M1436','M1435','M149','M157','M213','M699','M920','M871','M789','M617','M991','H903','M730','M191'],
  'CloneID': [0,1,2,2,2,2,2,2,3,3,3,4,4,4,5,5,6],
  'Length': [48,42  ,48,48,48,48,48,48,48,48,48,48,48,48,48,48,48]}

df = pd.DataFrame(df)

它看起来像:

df
Out[6]: 
    CloneID   ID  Length
0       0   H900      48
1       1   H901      42
2       2   H902      48
3       2   M1436     48
4       2   M1435     48
5       2   M149      48
6       2   M157      48
7       2   M213      48
8       3   M699      48
9       3   M920      48
10      3   M871      48
11      4   M789      48
12      4   M617      48
13      4   M991      48
14      5   H903      48
15      5   M730      48
16      6   M191      48

我想将每个“克隆ID”输出到不同的输出文件,但这次只输出包含以“H”开头的ID的文件。

所以我想要的输出,4个输出文件:

第一个文件是“cloneID0.txt”

    CloneID   ID  Length
      0      H900      48

第二个文件是“CloneID1.txt”

    CloneID   ID  Length
      1      H901      42

第三个文件是“CloneID2.txt”

    CloneID   ID  Length
       2     H902      48
       2     M1436     48
       2     M1435     48
       2     M149      48
       2     M157      48
       2     M213      48

第二个文件是“CloneID5.txt”

    CloneID   ID  Length
      5     H903      48
      5     M730      48

因此将不存在“CloneID3.txt”、“CloneID4.txt”和“CloneID6.txt”,因为这些克隆没有任何以“H”开头的ID。

我的代码:

import pandas as pd
data = pd.read_csv('data.txt', sep = '\t')
gp = data.groupby('CloneID')
for g in gp.groups:
    for s in data.ID:
        if s.startswith("H"):
           path = 'IgHCloneID' + str(g) + '.xlsx'
           gp.get_group(g).to_excel(path, index=False)

它仍然提供了所有的克隆文件,而不仅仅是那些包含以“H”开头的id的文件。你知道吗


Tags: 文件txtidpandasdfdatalengthpd
3条回答

创建一个要遍历的克隆id列表,然后将数据帧过滤到id字符串的第一个值为H的克隆id,然后输出到文本。你知道吗

代码

import pandas as pd

df = {'ID': ['H900','H901','H902','M1436','M1435','M149','M157','M213','M699','M920','M871','M789','M617','M991','H903','M730','M191'],
  'CloneID': [0,1,2,2,2,2,2,2,3,3,3,4,4,4,5,5,6],
  'Length': [48,42  ,48,48,48,48,48,48,48,48,48,48,48,48,48,48,48]}

df = pd.DataFrame(df)

clone_list = df['CloneID'].drop_duplicates().values.tolist()

for c in clone_list:
    clone_df = df.loc[df['CloneID'] == c]
    clone_df = clone_df.loc[(clone_df['ID'].str[0] == 'H') | (clone_df['ID'].str[0] == 'M')]
    #Create your text file here
    print clone_df

结果

    CloneID    ID  Length
0        0  H900      48
   CloneID    ID  Length
1        1  H901      42
   CloneID     ID  Length
2        2   H902      48
3        2  M1436      48
4        2  M1435      48
5        2   M149      48
6        2   M157      48
7        2   M213      48
    CloneID    ID  Length
8         3  M699      48
9         3  M920      48
10        3  M871      48
    CloneID    ID  Length
11        4  M789      48
12        4  M617      48
13        4  M991      48
    CloneID    ID  Length
14        5  H903      48
15        5  M730      48
    CloneID    ID  Length
16        6  M191      48

您可以groupbyCloneID并使用apply方法直接写入csv:

df.groupby('CloneID').apply(lambda gp: gp.to_csv('CloneID{}.txt'.format(gp.name)))

这将保留原始索引,但可以在调用to_csv之前通过.set_index('CloneID')修复它。你知道吗

编辑:仅保留相应的IDH开头的组:

这需要对每个组进行检查;这里有一种方法:

df.groupby('CloneID').apply(
    lambda gp: gp.to_csv('CloneID{}.txt'.format(gp.name))
    if any(gp.ID.str.startswith('H'))
    else None)

您可以在ID^{}'H'列的^{}值中按条件第一个^{},最后一个^{}使用^{}

df1 = (df.groupby('CloneID').filter(lambda x: (x.ID.str.startswith("H").any())))

df1.groupby('CloneID').apply(lambda x: x.to_csv('CloneID{}.txt'.format(x.name), index=False))

相关问题 更多 >