【问题标题】:Quick slicing of a dataframe using another dataframe in pandas使用 pandas 中的另一个数据帧快速切片数据帧
【发布时间】:2016-07-15 18:01:12
【问题描述】:

我在 pandas 中有两个数据框。 DF "A" 包含区域名称的开始和结束索引。 DF "B" 包含子区域的开始和结束索引。目标是提取所有区域的所有子区域。

例子:

A:

 start index | end index | zone name 
-----------------------------------
   1         |  10       |    X

B:
 start index | end index | subzone name 
-----------------------------------
   2         |  3        |    Y

在上面的示例中,Y 是 X 的子区域,因为它的索引位于 X 的索引内。

我目前这样做的方式是使用 iterrows 遍历 A 中的每一行,并且对于每一行(区域),我在 B(子区域)中找到切片。 这个解决方案在 pandas 中非常慢,因为 iterrows 不快。在 pandas 中不使用 iterrows 的情况下如何完成这项任务?

【问题讨论】:

  • 您可以使用thisthis 技术进行矢量化解决方案...

标签: python pandas dataframe


【解决方案1】:

可以使用字典和系列进行分组, 分组信息可以以数组以外的形式存在。让我们考虑另一个 示例 DataFrame (因为您的 Data Frames 没有 Data 我要使用我自己的 DF DFA =mapping, DFB= people 具有价值并具有现实世界的解释):

people = pd.DataFrame(np.random.randn(5, 5),
         columns=['a', 'b', 'c', 'd', 'e'],
         index=['Joe', 'Steve', 'Wes', 'Jim', 'Travis'])
people.iloc[2:3, [1, 2]] = np.nan # Add a few NA values

现在,假设我有一个列的组对应关系并想要求和 按组将列放在一起:

mapping = {'a': 'red', 'b': 'red', 'c': 'blue',
           'd': 'blue', 'e': 'red', 'f' : 'orange'}
#Mapping is a Dictionary just like a DataFrame (DF A representing Zones)

你可以从这个dict构造一个数组来传递给groupby,但是我们 可以只传递字典(我确定你可以在 Dictionary 转换为 dtata Frame 和 Data Frame 到 Dictionary,所以跳过这一步,否则你可以在 cmets 中询问)

by_column = people.groupby(mapping, axis=1)

我正在使用 sum() 运算符,你可以使用任何你想要的运算符(如果你想将子区域与父区域结合起来,你可以通过串联来做到这一点 - 否则我会详细介绍)

by_column.sum()

Series 具有相同的功能,可以将其视为固定大小的映射:

注意:使用带有数组、字典或系列的函数不是问题,因为所有内容都会在内部转换为数组。

【讨论】:

    猜你喜欢
    • 2019-10-29
    • 2018-02-12
    • 2017-11-16
    • 2019-10-25
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 2020-09-20
    • 2018-03-09
    相关资源
    最近更新 更多