【问题标题】:Concatenating DataFrames and offsetting integer indices连接 DataFrame 和偏移整数索引
【发布时间】:2021-07-29 16:17:01
【问题描述】:

我有一个检索到的 DataFrame 的字典,我想将它们连接到一个大的 DataFrame 中。每个 DataFrame 被依次检索,每个 DataFrame 都有一个索引列,它是从0n-1 的整数索引。每个数据帧最多有 n 个数据帧。

for i in range(no_of_pages):
        records_offset = i * records_limit
        response = my_api_client.get_dataframes(limit=records_limit,                                        
                                                offset=records_offset)
        page = response.get_result()
        pages[i] = page

页面的每个 DataFrame 值看起来像:

    a    b    c 
0   1    1    "Dog"   
1   0    0    "Monkey"   
2   0    0    "Banana"   
3   1    1    "Cat"   
4   1    0    "Blue Whale"   
..  ... ...  ...
999 0    1    "Pangolin"   

下一页可能如下所示:

    a    b    c 
0   1    1    "Clownfish"   
1   1    1    "Tompot Blenny"   
2   0    0    "Scorpionfish"   
3   0    1    "Grey Seal"   
4   0    0    "Beluga Whale"   
..  ... ...  ...
56  0    0    "Bearing Sea Cow"   

我的目标是对所有 DataFrame 页面执行pd.concat(),但将records_offset 添加到索引列。

    a    b    c 
0   1    1    "Dog"   
1   0    0    "Monkey"   
2   0    0    "Banana"   
3   1    1    "Cat"   
4   1    0    "Blue Whale"   
..  ... ...  ...
1056  0    0    "Bearing Sea Cow"    

在循环添加到字典之前,有没有一种简单的方法可以在循环中实现这一点?

【问题讨论】:

    标签: python pandas for-loop concatenation


    【解决方案1】:

    重新设置索引怎么样

    result = pd.concat[pages.values()].reset_index(drop=True)
    

    【讨论】:

      猜你喜欢
      • 2013-11-18
      • 2014-07-19
      • 2021-08-31
      • 2018-12-31
      • 2017-11-04
      • 1970-01-01
      • 2021-06-20
      • 2019-06-05
      相关资源
      最近更新 更多