【问题标题】:How do i add column header, in the second row in a pandas dataframe?如何在熊猫数据框的第二行添加列标题?
【发布时间】:2019-06-16 21:49:05
【问题描述】:

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

期望的输出:

我的代码:

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)

【问题讨论】:

  • 您能否通过edit to your question 准确地向我们展示您的输入和所需输出?
  • 我已经编辑了问题以显示所需的输出

标签: python python-3.x pandas csv


【解决方案1】:

你应该看看DataFrame.read_csvheader 关键字参数允许您在文件中指明用于标题名称的行。

你可能会这样做:

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

【讨论】:

    【解决方案2】:

    您可以使用csv 模块将数据框写入同一个文件之前写入一行。请注意,这在读回 Pandas 时无济于事,它不适用于“重复标题”。您可以创建 MultiIndex 列,但这不是您想要的输出所必需的。

    import pandas as pd
    import csv
    from io import StringIO
    
    # input file
    x = """A,B,C
    1,2,3
    red,blue,green"""
    
    # replace StringIO(x) with 'file.txt'
    df = pd.read_csv(StringIO(x))
    
    with open('file.txt', 'w', newline='') as fout:
        writer = csv.writer(fout)
        writer.writerow(['Type', 'Type2', 'Type3'])
        df.to_csv(fout, index=False)
    
    # read file to check output is correct
    df = pd.read_csv('file.txt')
    
    print(df)
    
    #   Type Type2  Type3
    # 0    A     B      C
    # 1    1     2      3
    # 2  red  blue  green
    

    【讨论】:

      【解决方案3】:

      因此,如果我理解正确,您有一个包含您的数据的文件“file.txt”,以及一个包含您的数据类型的列表。 您想将类型列表添加到数据的 pandas.DataFrame 中。对吗?

      如果是这样,您可以使用 pandas.read_csv() 将 txt 文件中的数据读入 pandas.df,然后使用 df.columns 定义列标题。

      所以它看起来像: df = pd.read_csv("file1.txt", header=None) df.columns = data_type[0:6]

      我希望这会有所帮助! 干杯

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-04
        • 1970-01-01
        • 2018-03-02
        • 2022-09-24
        • 1970-01-01
        • 2018-02-28
        • 2023-03-17
        • 1970-01-01
        相关资源
        最近更新 更多