如何用concat替换pandas的append?

3

你能帮我把这段代码中的 "append" 替换成 "concat" 吗?

saida = pd.DataFrame()
for x, y in lCodigos.items():
try:
    df = consulta_bc(x)
    logging.info(f'Indice {y} lido com sucesso.')
except Exception as err:
    logging.error(err)
    logging.warning('Rotina Indice falhou!')
    exit()
df['nome'] = y
saida = saida.append(df)   
print(saida)
3个回答

2

saida = pd.concat([saida, df], axis=1)

上述代码可代替以下代码 (如果您想将数据框“叠加在一起”,请设置axis=0)

saida = saida.append(df)


axis=0 是正确的。 - Dong-gyun Kim

1

只需使用列表保存“数据框部分”,并在最后使用pd.concat处理该数据框列表即可:

saida = list()  # Now use a list
for x, y in lCodigos.items():
    # ... your original code
    saida.append(df)
saida = pd.concat(saida)  # You can now create the dataframe

追踪(Traceback)最近的一次调用: 文件“c:/Py/Postgres/Vers3/xlogIND3.py”,第35行,在<module>中: saida = saida.append(df) 属性错误:'NoneType'对象没有'append'属性。 - Fcoatis
抱歉,已修复。问题在于在每个循环的末尾重新定义了saida(不应该这样做)。 - aaossa

0

在我的系统中它没有起作用。获取列表后:

saidaAdd = pd.DataFrame(saida)  # now you have the dataframe

FullFile = concat(['original_file', saidaAdd], axis =0)
# is probably what was intended to build records

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接