How to add an empty column to a dataframe?

后端 未结 11 598
自闭症患者
自闭症患者 2020-11-28 01:06

What\'s the easiest way to add an empty column to a pandas DataFrame object? The best I\'ve stumbled upon is something like

df[\'foo\'] = df.ap         


        
相关标签:
11条回答
  • 2020-11-28 01:34

    an even simpler solution is:

    df = df.reindex(columns = header_list)                
    

    where "header_list" is a list of the headers you want to appear.

    any header included in the list that is not found already in the dataframe will be added with blank cells below.

    so if

    header_list = ['a','b','c', 'd']
    

    then c and d will be added as columns with blank cells

    0 讨论(0)
  • 2020-11-28 01:35

    I like:

    df['new'] = pd.Series(dtype='your_required_dtype')
    

    If you have an empty dataframe, this solution makes sure that no new row containing only NaN is added.

    Specifying dtype is not strictly necessary, however newer Pandas versions produce a DeprecationWarning if not specified.

    0 讨论(0)
  • 2020-11-28 01:38

    if you want to add column name from a list

    df=pd.DataFrame()
    a=['col1','col2','col3','col4']
    for i in a:
        df[i]=np.nan
    
    0 讨论(0)
  • 2020-11-28 01:38

    You can do

    df['column'] = None #This works. This will create a new column with None type
    df.column = None #This will work only when the column is already present in the dataframe 
    
    0 讨论(0)
  • 2020-11-28 01:39

    The below code address the question "How do I add n number of empty columns to my existing dataframe". In the interest of keeping solutions to similar problems in one place, I am adding it here.

    Approach 1 (to create 64 additional columns with column names from 1-64)

    m = list(range(1,65,1)) 
    dd=pd.DataFrame(columns=m)
    df.join(dd).replace(np.nan,'') #df is the dataframe that already exists
    

    Approach 2 (to create 64 additional columns with column names from 1-64)

    df.reindex(df.columns.tolist() + list(range(1,65,1)), axis=1).replace(np.nan,'')
    
    0 讨论(0)
提交回复
热议问题