python - 如何在 pandas 数据框中的第二行添加列标题?

标签 python python-3.x pandas csv

我有一个来自 pandas 的数据框,现在我想添加列名称,但仅限于第二行。这是我之前的输出示例:

enter image description here

期望的输出:

enter image description here

我的代码:

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)

最佳答案

您应该看看DataFrame.read_csvheader 关键字参数允许您指示文件中用于 header 名称的行。

你可能可以用类似的方法来做到这一点:

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

在我的 python shell 中我测试了它:

>>> 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

关于python - 如何在 pandas 数据框中的第二行添加列标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54324968/

相关文章:

python-3.x - 根据其他列值对多个数据框列进行分组

python - 使用字典值在两个日期之间进行 Pandas Dataframe 查询

python - 使用 django 在 base.html 上填充 bootstrap 下拉列表

python - 有效地检查字符串列表中的字符串中的单词

python - 将嵌套的字典列表转换为 pandas DataFrame

python3.6 : equivalent of %d %s using the format: f("string {var1} {var2})

python - 如何为包含特定项目的列表过滤 DataFrame 列

java - 适合 12 岁 child 学习的好书?

python - 如何在 Python 中散列变量?

python - 如何从 Pandas 系列中仅提取大写子字符串?