Assigning column names from a list to a table

前端 未结 2 876
小鲜肉
小鲜肉 2021-01-02 07:59

I have, say, a 100 row by 25 column data table with no column headers. I have a 25-item list that I would like to assign as the column headers to the data table (they\'re in

相关标签:
2条回答
  • 2021-01-02 08:12

    There is a names argument for read_csv:

    names : array-like
          List of column names to use. If file contains no header row, then you
          should explicitly pass header=None

    That is, you want to be doing something like:

    df = pd.read_csv(fie_name, header=None, names=col_headers_list)
    
    0 讨论(0)
  • 2021-01-02 08:19

    You can just assign to the columns attribute directly.

    >>> import pandas
    >>> # create three rows of [0, 1, 2]
    >>> df = pandas.DataFrame([range(3), range(3), range(3)])
    >>> print df
       0  1  2
    0  0  1  2
    1  0  1  2
    2  0  1  2
    >>> my_columns = ["a", "b", "c"]
    >>> df.columns = my_columns
    >>> print df
       a  b  c
    0  0  1  2
    1  0  1  2
    2  0  1  2
    

    You can also assign to index to accomplish something similar

    >>> df.index = ["row1", "row2", "row3"]
    >>> print df
          a  b  c
    row1  0  1  2
    row2  0  1  2
    row3  0  1  2
    
    0 讨论(0)
提交回复
热议问题