gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:02:57 29 4
gpt4 key购买 nike

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

输出:

   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

关于python - 将数据附加到 Pandas 全局数据框变量不会持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59124407/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com