python - 将数据附加到 Pandas 全局数据框变量不会持久

https://www.coder.work/article/5047954

我正在尝试使用 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()

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

 

 

posted @ 2023-08-12 17:57  liushao-AI  阅读(37)  评论(0编辑  收藏  举报