pandas 的apply返回多列,并赋值

  • Post author:
  • Post category:其他

转载他人的,本来自己想写,算了

import pandas as pd
df_tmp = pd.DataFrame([
    {"a":"data1", "cnt":100},{"a":"data2", "cnt":200},
])
df_tmp
a	cnt
data1	100
data2	200
方法一:使用apply 的参数result_type 来处理
def formatrow(row):
    a = row["a"] + str(row["cnt"])
    b = str(row["cnt"]) + row["a"]
    return a, b 

df_tmp[["fomat1", "format2"]] = df_tmp.apply(formatrow, axis=1, result_type="expand")
df_tmp
a	cnt	fomat1	format2
data1	100	data1100	100data1
data2	200	data2200	200data2
方法一:使用zip打包返回结果来处理
df_tmp["fomat1-1"], df_tmp["format2-2"] = zip(*df_tmp.apply(formatrow, axis=1))
df_tmp
a	cnt	fomat1	format2	fomat1-1	format2-2
data1	100	data1100	100data1	data1100	100data1
data2	200	data2200	200data2	data2200	200data2