Python 如何将数据帧行转换为列?
我有以下格式的数据集/数据帧:Python 如何将数据帧行转换为列?,python,shell,Python,Shell,我有以下格式的数据集/数据帧: gene : ABC sample: XYX input:23 . . . gene : DEF sample: ERT input :24 . . 它一直在继续 我如何以这种格式获取它 gene sample input abc xyx 23 def ert 24 . . Python或shell命令都可以 我试过pd转置,但似乎没有给我想要的结果, 没有得到所需的输出。我不能100%确定您在寻找什么。我将给出几个潜在解决方案的示例。如
gene : ABC
sample: XYX
input:23
.
.
.
gene : DEF
sample: ERT
input :24
.
.
它一直在继续
我如何以这种格式获取它
gene sample input
abc xyx 23
def ert 24
.
.
Python或shell命令都可以
我试过pd转置,但似乎没有给我想要的结果,
没有得到所需的输出。我不能100%确定您在寻找什么。我将给出几个潜在解决方案的示例。如果这些不符合您的要求,请更新您的问题或添加评论 设置(按照您的示例信息): df的输出如下所示:
gene sample input
0 ABC XYZ 23
1 DEF ERT 24
这看起来像是你在问的问题。如果这是真的,您可以使用类似的设置(如开头的代码块)来设置此数据帧
如果你的意思是你有这种格式,并且你想转置它,我建议如下:
# 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
您需要将其读入并放入数据帧(类似于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)
这将逐行读取您的文件,并创建一个字典列表,很容易将其转换为数据帧。如果需要实际的csv文件,可以运行df.to\u csv(“name\u of\u file.csv”)
希望这些帮助之一
编辑:
要查看目录中的所有文件,可以在循环前面添加以下代码:
import glob
for filename in glob.glob("/your/path/here/*.txt"):
# code you want to execute
编辑:
这个问题似乎与被问的问题无关(见本答案的评论)。作者似乎有.tsv文件,这些文件已经是DataFrame格式的,他们希望这些文件作为DataFrame读入。给出的示例文件是:
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的示例代码:
这将创建一个包含基因数据的数据框。如果这创建了您要查找的数据集,请将此答案标记为已接受。如果您还有其他问题,请问一个新问题(在问题中发布数据文件非常有用)。我希望以csv格式输出,以gene、sample和input作为标题,下面的其余信息很难理解您的数据输入和输出。你说你正在使用一个数据框,所以也许可以看看并重新格式化你的样本数据,这样我们就可以帮助你更好地基本上是一个数据集-更像一个文本文件我的编辑帮助?如果每个文件都包含一个基因,那么您可以为每个文件添加一个字典。您还可以将所有这些文本文件连接到一个大文本文件中,并将其读入。这确实有帮助,但我不断得到错误-值错误-需要超过1个值才能解包。很难知道您遇到了什么错误,因为我看不到您的数据文件。错误发生在哪里?如果您的数据每行有多个“:”,这将是一个问题。@foodar,您必须发布一个指向该文件的链接或粘贴整个文件。“这十个字我做不了多少。@foondar我已经添加了您的数据文件和将数据收集到数据框中的代码。”。如果您还有其他问题,请将此答案标记为已接受,并创建一个新问题,以更准确地描述您的问题。
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
#!/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)