防止python返回类型解包数据帧

最棒的

我有一个像下面这样写的函数。

基本上我想使用每个函数的输出作为下一个(后续)函数的输入。不知道为什么最后一个函数会抛出错误。可以帮助我解决此错误吗?

def fun_1():
    print("Reading files")
    test_df = pd.read_csv('test.csv')
    test_df = test_df.replace('-',np.nan,regex=True)
    test_map = pd.read_excel('test_map.xlsx')
    test_map = test_map.apply(lambda x: x.astype(str).str.upper())
    return test_df,test_map 

def fun_2(test_df,test_map):
    print("formatting data types and structure")
    test_df['test_datetime'] = test_df['DATE'] +" " + test_df['TIME']
    test_df= test_df.apply(lambda x: x.astype(str).str.upper())
    test_df['test_datetime'] = pd.to_datetime(test_df['test_datetime'])
    return test_df, test_map 

def fun_3(test_df,test_map):
    print("applying data transformation")
    test_df['person_id'] = test_df['subject_id'].map(test_map)
    return test_clean_df

def fun_4(test_clean_df):
    test_clean_df.to_csv('test_clean_df.csv',index=False)
    print("file written")
    return test_clean_df

funcs = [fun_1,fun_2,fun_3,fun_4]

output = []
for func in funcs:
    print(output)
    output = func(*output)

我收到以下错误

类型错误:fun_4() 需要 1 个位置参数,但给出了 7 个

亚历克斯

当您调用 finaloutput = func(*output)funcfun_4您是在什么时候解包pandas.DataFrame对象。这将列作为位置参数传递:

In [1]: import pandas as pd
In [2]: df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
In [3]: def f(*args):
   ...:     print(args)
In [4]: f(*df)
('col1', 'col2')
In [5]: f(*(df, df))
(   col1  col2
0     1     3
1     2     4,
   col1  col2
0     1     3
1     2     4)

如果你改变你fun_3返回一个元组(注意额外的,returna()),可以被解压缩到仅仅是数据帧。

In [1]: import pandas as pd
In [2]: def a():
   ...:     return (pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]}),)
In [3]: def b(df):
   ...:     print(df)
In [4]: fs = [a, b]
In [5]: out = []
In [6]: for f in fs:
   ...:     out = f(*out)
#    col1  col2
# 0     1     3
# 1     2     4

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章