【问题标题】:Transforming a series of tuples into a series of the nth element of each tuple将一系列元组转换为每个元组的第 n 个元素的系列
【发布时间】:2017-08-23 13:12:41
【问题描述】:

有没有一种干净的方法可以将元组的Series 转换为另一个由每个元组中的第一个(或第n 个)元素组成的Series?例如,

ser = pd.Series([ (0,1,2), (3,4,5) ])

应该转化成0和3组成的系列:

0  0
1  3

(其中 0,1 是索引)。谢谢。

【问题讨论】:

    标签: python-3.x pandas tuples apply series


    【解决方案1】:

    使用.str访问器:

    In [90]: ser.str[0]
    Out[90]:
    0    0
    1    3
    dtype: int64
    

    这是 AFAIK 向量化Series.str.get(N) 方法的缩写形式:

    In [92]: ser.str.get(0)
    Out[92]:
    0    0
    1    3
    dtype: int64
    

    【讨论】:

    • 漂亮,你能评论一下为什么这样有效吗?我之所以这么问是因为我很惊讶您调用了.str,因为它通常与字符串有关,而这里我们有一个元组。
    【解决方案2】:

    您可以使用Series.apply 将任意函数应用于您的系列。 operator.itemgetter 将返回一个访问您想要访问的任何成员的函数:

    get0 = operator.itemgetter(0)
    my0 = myseries.apply(get0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 2019-04-21
      相关资源
      最近更新 更多