如何在Pandas数据帧的第二行中添加列标题? [英] How do i add column header, in the second row in a pandas dataframe?

查看:66
本文介绍了如何在Pandas数据帧的第二行中添加列标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自熊猫的数据框框架,现在我想添加列名,但仅适用于第二行.这是我以前的输出的示例:

I have a data frame frame from pandas and now I want to add columns names, but only for the second row. Here is an example of my previous output:

所需的输出:

我的代码:

data_line=open("file1.txt", mode="r")

lines=[]
for line in data_line:
    lines.append(line)
for i, line in enumerate(lines):
    # print('{}={}'.format(i+1, line.strip()))
    file1_header=lines[0] 
num_line=1
Dictionary_File1={}
Value_File1= data_type[0:6]
Value_File1_short=[]
i=1
for element in Value_File1:
    type=element.split(',')
    Value_File1_short.append(type[0] + ", " + type[1] + ", " + type[4])
    i += 1
Dictionary_File1[ file1_header]=Value_File1_short
pd_file1=pd.DataFrame.from_dict(Dictionary_File1)

推荐答案

您应该查看

You should have a look at DataFrame.read_csv. The header keyword parameter allows you to indicate a line in the file to use for header names.

您可能可以使用类似的方法做到这一点:

You could probably do it with something like:

pd.read_csv("file1.txt", header=1)

在我的python shell中,我用以下方法对其进行了测试:

From my python shell I tested it out with:

>>> from io import StringIO # I use python3
>>> import pandas as pd
>>> >>> data = """Type    Type2   Type3
... A           B   C
... 1           2   3
... red     blue    green""" 
>>> # StringIO below allows us to use "data" as input to read_csv
>>> # "sep" keyword is used to indicate how columns are separated in data
>>> df = pd.read_csv(StringIO(data), header=1, sep='\s+')
>>> df
     A     B      C
0    1     2      3
1  red  blue  green

这篇关于如何在Pandas数据帧的第二行中添加列标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆