Python 3.x 将数据附加到字典中的DataFrame实例

Python 3.x 将数据附加到字典中的DataFrame实例,python-3.x,pandas,Python 3.x,Pandas,在我的问题中,我试图定义一个数据帧(ex),并在计算过程中在其中存储一些值 下面是我的问题的一个简短示例: 将熊猫作为pd导入 def main(): ex1=pd.DataFrame(列=['Timestamp','A']) ex2=pd.DataFrame(列=['Timestamp','A']) str1='hello-1' str2='hello-2' tcp_hash={1:(ex1,str1),2:(ex2,str2)} 对于范围(5)内的idx: 尝试: (df,str_idx)=

在我的问题中,我试图定义一个数据帧(ex),并在计算过程中在其中存储一些值

下面是我的问题的一个简短示例:

将熊猫作为pd导入
def main():
ex1=pd.DataFrame(列=['Timestamp','A'])
ex2=pd.DataFrame(列=['Timestamp','A'])
str1='hello-1'
str2='hello-2'
tcp_hash={1:(ex1,str1),2:(ex2,str2)}
对于范围(5)内的idx:
尝试:
(df,str_idx)=tcp_hash.get(idx,None)
append({'Timestamp':idx,'A':str\u idx},ignore\u index=True)
tcp_hash[idx]=(df,str_idx)
除类型错误外:
打印('TCP消息:{}没有语法分析器'。格式(idx))
打印(ex1)
打印(ex2)
如果名称=“\uuuuu main\uuuuuuuu”:
main()
由于我的前任,我得到:

TCP消息:0没有解析器
TCP消息:3没有解析器
TCP消息:4没有解析器
空数据帧
列:[时间戳,A]
索引:[]
空数据帧
列:[时间戳,A]
索引:[]
而不是:

时间戳A
0 1你好-1

时间戳A
0 2你好-2
如果我正确理解了我的问题,那么我猜ex inside tcp_hash_uu是我的ex的副本,而不是“引用”


我如何修复我的代码?

我只是修复了你的代码。熊猫
df.append
将创建新对象。因此,
append
产生的任何数据帧结果不再是原始的
ex1
ex2
。您可以使用
loc
内联修改
ex1
ex2
,如下所示

def main():
    ex1 = pd.DataFrame(columns=['Timestamp','A'])
    ex2 = pd.DataFrame(columns=['Timestamp','A'])
    str1 = 'hello-1'
    str2 = 'hello-2'
    tcp_hash = { 1 : (ex1, str1), 2 : (ex2, str2) }

    for idx in range(5):
        try:
            (df, str_idx) = tcp_hash.get(idx, None)
            #df.append({'Timestamp': idx, 'A': str_idx}, ignore_index=True)
            df.loc[df.shape[0], :] = {'Timestamp': idx, 'A': str_idx}
            tcp_hash[idx] = (df, str_idx)
        except TypeError:
            print('TCP Message: {} does not have a parser'.format(idx))

    print(ex1)
    print(ex2)

if __name__== "__main__":
    main()    
输出

TCP Message: 0 does not have a parser
TCP Message: 3 does not have a parser
TCP Message: 4 does not have a parser
  Timestamp        A
0  1         hello-1
  Timestamp        A
0  2         hello-2

谢谢你的回答。我修改了我的代码,以便更多地解释我的问题的复杂性以及为什么我不能使用您的答案。我正在尝试一个通用的解决方案,因为我不知道确切的数据帧。@Eagle:由于数据帧的易变性,
ex1
ex2
外部和内部dict是相同的对象。但是,它们最初都是空的。您需要有代码来为它们赋值。这就是你的代码缺失的部分。我修改了我的代码,使之符合我认为你的要求。它越不想工作…@Eagle:
df.append
将创建一个新对象。因此,在调用它之后,它不再是原始的
ex1
ex2
对象。我编辑了答案以使用其他方法。检查我的编辑是否有可能提高性能?因为“分配”操作需要花费时间。数据帧的预分配空间是否会有所改善?