代码之家  ›  专栏  ›  技术社区  ›  noobie

将数据追加到Pandas gloabl dataframe变量不存在

  •  0
  • noobie  · 技术社区  · 5 年前

    我试图使用pandas dataframe全局变量。但是,当我尝试重新分配或将数据帧追加到全局变量时,它是空的感谢任何帮助。

    import pandas as pd
    
    df = pd.DataFrame()
    
    def my_func():
    
        global df
    
        d = pd.DataFrame()
    
        for i in range(10):
            dct = {
                "col1": i,
                "col2": 'value {}'.format(i)    
            }
    
            d.append(dct, ignore_index=True) 
            # df.append(dct, ignore_index=True) # Does not seem to append anything to the global variable
        df = d # does not assign any values to the global variable
    
    my_func()
    
    df.head()
    
    1 回复  |  直到 5 年前
        1
  •  0
  •   Chris    5 年前

    list.append , pandas.DataFrame.append 就地操作。稍微修改一下代码就可以了:

    import pandas as pd
    
    df = pd.DataFrame()
    
    def my_func():
        global df
        d = pd.DataFrame()
        for i in range(10):
            dct = {
                "col1": i,
                "col2": 'value {}'.format(i)}
            d = d.append(dct, ignore_index=True) # <<< Assignment needed
            # df.append(dct, ignore_index=True) # Does not seem to append anything to the global variable
        df = d # does not assign any values to the global variable
    
    my_func()
    
    df.head()
    

    输出:

       col1     col2
    0   0.0  value 0
    1   1.0  value 1
    2   2.0  value 2
    3   3.0  value 3
    4   4.0  value 4