如何更新一个数据帧给出一个元组列表和一个gen

2024-04-26 14:16:23 发布

您现在位置:Python中文网/ 问答频道 /正文

设置

考虑数据帧df

df = pd.DataFrame(
    np.arange(100).reshape(10, 10),
    list('ABCDEFGHIJ'), list('abcdefghij')
)

df

    a   b   c   d   e   f   g   h   i   j
A   0   1   2   3   4   5   6   7   8   9
B  10  11  12  13  14  15  16  17  18  19
C  20  21  22  23  24  25  26  27  28  29
D  30  31  32  33  34  35  36  37  38  39
E  40  41  42  43  44  45  46  47  48  49
F  50  51  52  53  54  55  56  57  58  59
G  60  61  62  63  64  65  66  67  68  69
H  70  71  72  73  74  75  76  77  78  79
I  80  81  82  83  84  85  86  87  88  89
J  90  91  92  93  94  95  96  97  98  99

元组列表tups

tups = [
    ('A', 'a'), ('A', 'h'), ('B', 'e'), ('C', 'b'),
    ('C', 'i'), ('D', 'f'), ('E', 'c'), ('E', 'j'),
    ('F', 'g'), ('G', 'd'), ('H', 'a'), ('H', 'h'),
    ('I', 'e'), ('J', 'b'), ('J', 'i')
]

和发生器fib

def fib():
    x0 = None
    x1 = None
    while True:
        if x0 is None:
            yield 0
            x0 = 0
        elif x1 is None:
            yield 1
            x1 = 1
        else:
            x0, x1 = x1, x1 + x0
            yield x1

问题

fibtups中的每个元组更新df的最有效或最优雅的方法是什么,其中每个元组表示df中的坐标,其中第一个元素是索引,第二个是列?你知道吗

我做了什么

f = fib()
for row, col in tups:
    df.set_value(row, col, next(f))

df

    a    b   c   d    e   f   g   h    i   j
A   0    1   2   3    4   5   6   1    8   9
B  10   11  12  13    1  15  16  17   18  19
C  20    2  22  23   24  25  26  27    3  29
D  30   31  32  33   34   5  36  37   38  39
E  40   41   8  43   44  45  46  47   48  13
F  50   51  52  53   54  55  21  57   58  59
G  60   61  62  34   64  65  66  67   68  69
H  55   71  72  73   74  75  76  89   78  79
I  80   81  82  83  144  85  86  87   88  89
J  90  233  92  93   94  95  96  97  377  99

Tags: 数据nonedataframedfiscollistrow
2条回答

如果没坏就别修了?但我还是会努力的:

f = fib()
tall = df.stack()
tall[tups] = tall[tups].apply(lambda x: next(f))
tall.unstack()

在查看DYZ解决方案时,我尝试对其进行一些优化,去掉apply和lambda。我认为这比DYZ的解快一倍。你知道吗

f = fib()
s1 = [next(f) for _ in range(len(tups))]
tall = df.stack()
tall[tups] = s1
tall.unstack()

相关问题 更多 >