簡體   English   中英

Pandas output 數據框中的 2 列使用 apply function 返回一個包含 2 個項目的元組/列表

[英]Pandas output 2 column in data frame using apply function which returns a tuple / list of 2 items

我有一個包含 10 列的數據框。 您可以使用此代碼生成一個名為df的示例框架。

cols = []
for i in range(1,11):
    cols.append(f'x{i}')

df = pd.DataFrame(np.random.randint(10,99,size=(10, 10)), columns=cols)

數據框看起來像這樣,它是隨機生成的,所以你的數字會有所不同。

    x1  x2  x3  x4  x5  x6  x7  x8  x9  x10
0   91  30  82  10  92  62  43  66  96  88
1   61  95  77  16  19  67  88  44  72  52
2   44  21  68  93  29  40  25  78  96  94
3   80  11  50  55  14  56  21  78  36  41
4   84  52  97  29  92  44  89  78  27  62
5   11  82  83  84  34  90  56  74  68  76
6   31  92  13  89  95  80  75  59  81  74
7   14  25  47  98  67  18  78  10  64  40
8   52  75  60  44  36  18  33  79  65  18
9   19  69  12  61  60  92  61  21  43  72

我想應用一個返回元組的 function。 我想使用元組在我的數據框中創建 2 列。

def some_func(i1,i2):
    o1 = i2 / i1 * 0.5
    o2 = i2 * o1 * 6
    return o1,o2

當我這樣做時,

df['c1'], df['c2'] = df.apply(lambda row: some_func(row['x9'],row['x10']), axis=1)

我得到這個錯誤,

ValueError: too many values to unpack (expected 2)

output 應該是這樣的,

    x1  x2  x3  x4  x5  x6  x7  x8  x9  x10 c1          c2
0   91  30  82  10  92  62  43  66  96  88  0.458333    242.000000
1   61  95  77  16  19  67  88  44  72  52  0.361111    112.666667
2   44  21  68  93  29  40  25  78  96  94  0.489583    276.125000
3   80  11  50  55  14  56  21  78  36  41  0.569444    140.083333
4   84  52  97  29  92  44  89  78  27  62  1.148148    427.111111
5   11  82  83  84  34  90  56  74  68  76  0.558824    254.823529
6   31  92  13  89  95  80  75  59  81  74  0.456790    202.814815
7   14  25  47  98  67  18  78  10  64  40  0.312500    75.000000
8   52  75  60  44  36  18  33  79  65  18  0.138462    14.953846
9   19  69  12  61  60  92  61  21  43  72  0.837209    361.674419

如果我只返回 1 output,並創建 1 列,它就可以正常工作。 我如何 output 2 項(元組或 2 項列表)並使用它創建 2 個新列?

必須有幾種方法。

我試着做你想做的,只做了一些改變。

  • 沒有lambda用法,因為您已經定義了自己的 function。
  • result_type="expand"apply()中,以便返回值將拆分為多個列。
  • Dataframe而不是兩個Series ,以便返回值可以拆分為 dataframe(由兩個Series組成)。
import pandas as pd

df = pd.DataFrame({
    'inputcol1': [1, 2, 3, 4],
    'inputcol2': [1, 2, 3, 4]
})


def some_func(x):
    output1 = x['inputcol1'] + x['inputcol2']
    output2 = x['inputcol2'] - x['inputcol2']
    return output1, output2

print(df)

#   inputcol1  inputcol2
#0          1          1
#1          2          2
#2          3          3
#3          4          4

df[['outputcol1', 'outputcol2']] = df[['inputcol1', 'inputcol2']].apply(some_func, axis=1, result_type="expand")

print(df)

#   inputcol1  inputcol2  outputcol1  outputcol2
#0          1          1           2           0
#1          2          2           4           0
#2          3          3           6           0
#3          4          4           8           0

由於您需要逐行遍歷多列,因此更好/更有效的方法是使用zip + for 循環創建一個元組列表,您可以直接將其分配給原始數據框的列列表:

df[['c1', 'c2']] = [some_func(x, y) for x, y in zip(df.x9, df.x10)]

df    
   x1  x2  x3  x4  x5  x6  x7  x8  x9  x10        c1          c2
0  20  67  76  95  28  60  82  81  90   93  0.516667  288.300000
1  94  30  97  82  51  10  54  43  36   41  0.569444  140.083333
2  50  57  85  48  67  65  41  91  48   46  0.479167  132.250000
3  61  36  44  59  18  71  42  18  56   77  0.687500  317.625000
4  11  85  34  66  45  55  21  42  77   27  0.175325   28.402597
5  20  19  86  46  97  21  84  12  86   98  0.569767  335.023256
6  24  87  65  62  22  43  26  80  15   64  2.133333  819.200000
7  38  15  23  22  89  89  19  32  21   33  0.785714  155.571429
8  82  88  64  89  92  88  15  30  85   83  0.488235  243.141176
9  96  24  91  70  96  54  57  81  59   32  0.271186   52.067797

先生成一個臨時的DataFrame:

wrk = df.apply(lambda row: some_func(row['x9'],row['x10']), axis=1)\
    .apply(pd.Series, index=['c1', 'c2'])

細節:

  • df.apply(…) - 您的代碼 - 從每一行元組創建,並將它們收集在一個Series中。
  • apply(pd.Series, index=['c1', 'c2']) - 從到目前為止生成的Series的每個元素(一個元組)創建一個Series ,其索引包含新的列名。 然后將這些Series對象收集到DataFrame中,其中源索引值現在是列名。

打印wrk以查看到目前為止生成的結果。

然后將它加入df並將結果保存回df下:

df = df.join(wrk)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM