Removing header column from pandas dataframe

前端 未结 4 602
眼角桃花
眼角桃花 2020-12-09 08:46

I have the foll. dataframe:

df

   A   B
0  23  12
1  21  44
2  98  21

How do I remove the column names A and B

相关标签:
4条回答
  • 2020-12-09 09:06

    How to get rid of a header(first row) and an index(first column).

    To write to CSV file:

    df = pandas.DataFrame(your_array)
    df.to_csv('your_array.csv', header=False, index=False)
    

    To read from CSV file:

    df = pandas.read_csv('your_array.csv')
    a = df.values
    

    If you want to read a CSV file that doesn't contain a header, pass additional parameter header:

    df = pandas.read_csv('your_array.csv', header=None)
    
    0 讨论(0)
  • 2020-12-09 09:10

    I had the same problem but solved it in this way:

    df = pd.read_csv('your-array.csv', skiprows=[0])
    
    0 讨论(0)
  • 2020-12-09 09:25

    I think you cant remove column names, only reset them by range with shape:

    print df.shape[1]
    2
    
    print range(df.shape[1])
    [0, 1]
    
    df.columns = range(df.shape[1])
    print df
        0   1
    0  23  12
    1  21  44
    2  98  21
    

    This is same as using to_csv and read_csv:

    print df.to_csv(header=None,index=False)
    23,12
    21,44
    98,21
    
    print pd.read_csv(io.StringIO(u""+df.to_csv(header=None,index=False)), header=None)
        0   1
    0  23  12
    1  21  44
    2  98  21
    

    Next solution with skiprows:

    print df.to_csv(index=False)
    A,B
    23,12
    21,44
    98,21
    
    print pd.read_csv(io.StringIO(u""+df.to_csv(index=False)), header=None, skiprows=1)
        0   1
    0  23  12
    1  21  44
    2  98  21
    
    0 讨论(0)
  • 2020-12-09 09:29

    Haven't seen this solution yet so here's how I did it without using read_csv:

    df.rename(columns={'A':'','B':''})
    

    If you rename all your column names to empty strings your table will return without a header.

    And if you have a lot of columns in your table you can just create a dictionary first instead of renaming manually:

    df_dict = dict.fromkeys(df.columns, '')
    df.rename(columns = df_dict)
    
    0 讨论(0)
提交回复
热议问题