簡體   English   中英

如何將數據框行轉換為列?

[英]How to convert dataframe rows into columns?

我有以下格式的數據集/數據框:

gene : ABC
sample: XYX
input:23
.
.
.
gene : DEF
sample: ERT
input :24

.
.

它會一直持續下去。

如何以這種格式獲取它?

gene sample input
abc   xyx   23
def    ert   24

.
.

Python或Shell命令都可以。

我嘗試了pd transpose,但隨后似乎沒有給我我想要的結果,沒有得到所需的輸出。

我不確定您要尋找什么。 我將給出一些潛在解決方案的示例。 如果這些與您的要求不符,請更新您的問題或添加評論。

設置(按照您的示例信息):

    import pandas as pd
    dict1 = {"gene": "ABC", "sample": "XYZ", "input": 23}
    dict2 = {"gene": "DEF", "sample": "ERT", "input": 24}
    columns = ["gene", "sample", "input"]
    df = pd.DataFrame([dict1, dict2], columns=columns)

df的輸出如下所示:

  gene sample  input
0  ABC    XYZ     23
1  DEF    ERT     24

看起來就像您在問題中尋找的東西。 如果是這樣,則可以使用類似的設置(例如開頭的代碼塊)來設置此DataFrame。

如果您想使用該格式,並且希望對其進行轉置,則建議以下內容:

    # columns will be the index from 0 to n-1:
    df.transpose()
    # output:
    #           0    1
    # gene    ABC  DEF
    # sample  XYZ  ERT
    # input    23   24

    # try this instead
    list_that_contains_n_items_to_be_columns = ["a", "b"]
    df.index = pd.Index(list_that_contains_n_items_to_be_columns)
    df.transpose()
    # output:
    #           a    b
    # gene    ABC  DEF
    # sample  XYZ  ERT
    # input    23   24

如果您的意思是將信息發布在文本文件中,例如:

gene : ABC
sample: XYX
input:23
gene : DEF
sample: ERT
input :24

您需要將其讀入並放入DataFrame中(類似於csv格式)。 您可以通過以下方式做到這一點:

import pandas as pd
list_of_dicts = []
with open("data.txt") as f:
    number_columns = 3 # change this as necessary
    line_num = 0
    for line in f:
        if line_num % number_columns == 0:
            if line_num == 0:
                dict_row = {}
            else:
                list_of_dicts.append(dict_row)
                dict_row = {}
        line_num += 1
        (key, val) = line.split(":")
        dict_row[str(key)] = val.rstrip()

# add your columns to that list
df = pd.DataFrame(list_of_dicts, columns=["gene", "sample", "input"])
print(df)

這將逐行讀取您的文件並創建字典列表,該列表很容易變成pandas DataFrame。 如果要使用實際的csv文件,則可以運行df.to_csv("name_of_file.csv")

希望這些幫助之一!

編輯:要查看目錄中的所有文件,可以在循環前面添加以下代碼:

    import glob
    for filename in glob.glob("/your/path/here/*.txt"):
        # code you want to execute

編輯編輯:

該問題似乎與所要詢問的內容無關(請參閱此答案的評論)。 似乎作者擁有已經是DataFrame風格的.tsv文件,他們希望這些文件作為DataFrames讀入。 給出的示例文件是:

Sample Name:    1234
Index:  IB04
Input DNA:  100

Detected ITD Variants:
Size    READS   VRF



Sample Name:    1235
Index:  IB05
Input DNA:  100

Detected Variants:
Size    READS   VRF
27  112995  4.44e-01
Total   112995  4.44e-01

讀取此文件並創建“樣本” DF的示例代碼:

#!/usr/bin/python
import os
import glob
import pandas as pd
os.chdir(os.getcwd())


def get_df(num_cols=3, start_key="Sample", switch_line=""):
    list_of_dfs = []
    for filepath in glob.glob("*.tsv"):
        list_of_dicts = []
        number_columns = num_cols
        line_num = 0
        part_of_df = False
        with open(filepath) as file:
            for line in file:
                # only read in lines to the df that are part of the dataframe
                if start_key in line:
                    part_of_df = True 
                elif line.strip() == "":
                    # if an empty line, go back to not adding it
                    part_of_df = False
                    continue
                if part_of_df:
                    # depending on the number of columns, add to the df
                    if line_num % number_columns == 0:
                        if line_num == 0:
                            dict_row = {}
                        else:
                            list_of_dicts.append(dict_row)
                            dict_row = {}
                    line_num += 1
                    (key, val) = line.split(":")
                    dict_row[str(key)] = val.rstrip().strip()
            if len(dict_row) % number_columns == 0:
                # if last added row is the last row of the file
                list_of_dicts.append(dict_row)
            df = pd.DataFrame(list_of_dicts, columns=['Sample Name','Index','Input DNA'])
        list_of_dfs.append(df)
    # concatenate all the files together
    final_df = pd.concat(list_of_dfs)
    return final_df

df_samples = get_df(num_cols=3, start_key="Sample", switch_line="")
print(df_samples)

這將創建一個包含基因數據的DataFrame。 如果這創建了您要查找的數據集,請將此答案標記為已接受。 如果您還有其他問題,請提出一個新問題(在問題中發布數據文件非常有幫助)。

暫無
暫無

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

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