繁体   English   中英

如何使用 apply(基于用户定义的函数)向数据框添加新行和多行?

[英]How to add new and multiple rows to a dataframe using apply (based on a user-defined function)?

对于我的用例,原始框架看起来像 -

指数 col1 col2 col3
0 0 第零个例如 拒绝
1 1 首先例如 接受
2 2 第二个例如 接受
3 3 第三个例如 拒绝

我有一个函数定义为 -

def foo(row):
  if row['col1']==0:
    answers = ['zero']
  elif row['col1']==1:
    answers = ['one', 'i']
  elif row['col1']==2:
    answers = ['two', 'ii']
  else:
    answers = ['three', 'iii']

基于这个函数,我想在我的数据框中添加一个名为 col4 的新列。 本质上,需要添加与answers列表中的值一样多的新行,其中每行中 col4 的值应该是列表的后续值(而所有其他列的值保持不变)

所以我希望得到的框架像 -

指数 col1 col2 col3 col4
0 0 第零个例如 拒绝
1 1 首先例如 接受
2 1 首先例如 接受 一世
3 2 第二个例如 接受
4 2 第二个例如 接受 ii
5 3 第三个例如 拒绝
6 3 第三个例如 拒绝

我无法理解我们如何使用 apply 来返回行以及多行。 下面的代码只会在包含列表的原始框架中添加一个新列 col4 (如果我在foo中返回答案)

input_df['col4'] = input_df.apply(foo, axis=1)

如何修改foo以返回多行? 任何帮助表示赞赏。

您可以尝试返回列表然后explode

def foo(row):
  if row['col1']==0:
    answers = ['zero']
  elif row['col1']==1:
    answers = ['one', 'i']
  elif row['col1']==2:
    answers = ['two', 'ii']
  else:
    answers = ['three', 'iii']

  return answers

input_df['col4'] = input_df.apply(foo, axis=1)
input_df = input_df.explode('col4', ignore_index=True)
print(input_df)

   index  col1       col2    col3   col4
0      0     0  zeroth eg  reject   zero
1      1     1   first eg  accept    one
2      1     1   first eg  accept      i
3      2     2  second eg  accept    two
4      2     2  second eg  accept     ii
5      3     3   third eg  reject  three
6      3     3   third eg  reject    iii

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM