Skip to content Skip to sidebar Skip to footer

How Do I Add Column Header, In The Second Row In A Pandas Dataframe?

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: Desired output: My code: data_li

Solution 1:

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)

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

Solution 2:

You can write a row using the csv module before writing your dataframe to the same file. Notice this won't help when reading back to Pandas, which doesn't work with "duplicate headers". You can create MultiIndex columns, but this isn't necessary for your desired output.

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

withopen('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

Solution 3:

So if I understand properly, you have a file "file.txt" containing your data, and a list containing the types of your data. You want to add the list of types, to the pandas.DataFrame of your data. Correct?

If so, you can read the data from the txt file into a pandas.df using pandas.read_csv(), and then define the columns headers using df.columns.

So it would look something like: df = pd.read_csv("file1.txt", header=None) df.columns = data_type[0:6]

I hope this helps! Cheers

Post a Comment for "How Do I Add Column Header, In The Second Row In A Pandas Dataframe?"