gpt4 book ai didi

python - 选择特定列仅在 Python 中形成数据框

转载 作者:太空宇宙 更新时间:2023-11-04 10:17:25 26 4
gpt4 key购买 nike

使用 python 和 pandas 作为 pd,我试图输出一个包含基于特定标题的列子集的文件。

这是一个输入文件的例子

gene_input = pd.read_table(args.gene, sep="\t" ,index_col=0)

gene_input的结构:

       Sample1  Sample2  Sample3  Sample4  Sample5  Sample6  Sample7  Sample8Gene1        2       23      213      213       13      132      213     4312Gene2        3       12    21312      123      123       23     4321      432Gene3        5      213    21312       15      516     3421     4312     4132Gene4        2      123      123        7      610       23     3214     4312Gene5        1      213      213        1      152       23     1423     3421

Using a different loop, I generated TWO dictionaries. The first one has the keys (Sample 1 and Sample 7) and the second has the keys (Sample 4 and 8).

I would like to have the following output (Note that I want the samples from each of the dictionaries to be consecutive; i.e. all Dictionary 1 first, then all Dictionary 2):The output that I am looking for is:

        Sample1 Sample7 Sample4 Sample8Gene1   2   213 213 4312Gene2   3   4321    123 432Gene3   5   4312    15  4132Gene4   2   3214    7   4312Gene5   1   1423    1   3421

I have tried the following but none worked:

key_num=list(dictionary1.keys())
num = genes_input[gene_input.columns.isin(key_num)]

为了提取第一组列然后以某种方式组合它,但是失败了。它一直给我属性错误,我确实更新了 Pandas 。我还尝试了以下方法:

reader = csv.reader( open(gene_input, 'rU'), delimiter='\t')
header_row = reader.next() # Gets the header

for key, value in numerator.items():
output.write(key + "\t")
if key in header_row:
for row in reader:
idx=header_row.index(key)
output.write(idx +"\t")

以及其他一些命令/循环/行。有时我只得到第一个键只出现在输出中,其他时候我得到一个错误;取决于我尝试的方法(为了方便起见,我没有在此处列出所有方法)。

无论如何,如果有人对我如何生成感兴趣的输出文件有任何意见,我将不胜感激。

同样,这是我想要的最终输出:

        Sample1 Sample7 Sample4 Sample8Gene1   2   213 213 4312Gene2   3   4321    123 432Gene3   5   4312    15  4132Gene4   2   3214    7   4312Gene5   1   1423    1   3421

最佳答案

对于特定顺序的一组特定列,使用:
df = gene_input[['Sample1', 'Sample2', 'Sample4', 'Sample7']]

如果您需要自动生成该列表 (['Sample1',...]),并且名称已给定,您应该能够构建两个列表,将它们合并然后排序:
column_names = sorted(dictionary1.keys() + dictionary2.keys())

您拥有的名称应该正确排序。对于输出,您应该能够使用:
df.to_csv(<output file name>, sep='\t')

编辑:添加了关于输出的部分

关于python - 选择特定列仅在 Python 中形成数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34477089/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com