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 @   liushao-AI  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示