Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在dataframe列上应用函数以获取其他几个列_Python_Pandas_Dataframe_Apply - Fatal编程技术网

Python 在dataframe列上应用函数以获取其他几个列

Python 在dataframe列上应用函数以获取其他几个列,python,pandas,dataframe,apply,Python,Pandas,Dataframe,Apply,我有一个数千行的数据帧。我想在单个列上应用一个函数,以便获得其他7列并将其合并到dataframe。 数据帧示例: df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6]}) a b 0 1 4 1 2 5 2 3 6 函数的示例。该函数返回一个数据帧 def function(x): return pd.DataFrame({'c':[x+2],'d':[x*2],'e':[x%2],'f':[x/2],'g':[x-

我有一个数千行的数据帧。我想在单个列上应用一个函数,以便获得其他7列并将其合并到dataframe。 数据帧示例:

df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6]})
    a   b
0   1   4
1   2   5
2   3   6
函数的示例。该函数返回一个数据帧

def function(x):
    return pd.DataFrame({'c':[x+2],'d':[x*2],'e':[x%2],'f':[x/2],'g':[x-2],'h':[x**2],'i':[x*x]})
我尝试执行的操作会出现错误:

df[['c','d','e','f','g','h','i']] = df['a'].apply(lambda x: function(x))
预期产出:

    a   b   c   d   e   f   g   h   i
0   1   4   3   2   1   0.5 -1  1   1
1   2   5   4   4   0   1.0 0   4   4
2   3   6   5   6   1   1.5 1   9   9

返回一个
pd.Series
而不是
pd.DataFrame

def function(x):
    return pd.DataFrame({'c':[x+2],'d':[x*2],'e':[x%2],'f':[x/2],'g':[x-2],'h':[x**2],'i':[x*x]}).loc[0]
或者


返回一个
pd.Series
而不是
pd.DataFrame

def function(x):
    return pd.DataFrame({'c':[x+2],'d':[x*2],'e':[x%2],'f':[x/2],'g':[x-2],'h':[x**2],'i':[x*x]}).loc[0]
或者


您需要从
DataFrame
构造函数中删除
[]
,要处理列
a
中的值,请使用:


您需要从
DataFrame
构造函数中删除
[]
,要处理列
a
中的值,请使用:


对于我给出的具体例子,这解决了这个问题。但是,我有一个更复杂的函数,其中我使用split()来拆分字符串,然后处理列表。这种方法不起作用,因为它接受序列并给出一个错误AttributeError:“Series”对象没有属性“split”任何提示?@AliSultan-在没有数据的情况下不容易回答,您认为
Series.str.split()吗
like?请查看我在那里添加代码的其他问题的链接,因为在这里添加代码很困难,因为我给出的具体示例解决了这个问题。但是,我有一个更复杂的函数,其中我使用split()来拆分字符串,然后处理列表。这种方法不起作用,因为它接受序列并给出一个错误AttributeError:“Series”对象没有属性“split”任何提示?@AliSultan-在没有数据的情况下不容易回答,您认为
Series.str.split()吗
like?请查看另一个问题的链接,我在那里添加了代码,因为很难将其添加到此处。这不起作用。它给出了一个ValueError:当使用iterableThis设置时,必须具有相等的len键和值。这不起作用。它给出了一个ValueError:当使用iterable设置时,必须具有相等的len键和值
def function(x):
    return pd.DataFrame({'c':x+2,'d':x*2,'e':x%2,'f':x/2,'g':x-2,'h':x**2,'i':x*x})  


df[['c','d','e','f','g','h','i']] = df['a'].pipe(function)
#alternative
#df[['c','d','e','f','g','h','i']] = function(df['a'])
print (df)
   a  b  c  d  e    f  g  h  i
0  1  4  3  2  1  0.5 -1  1  1
1  2  5  4  4  0  1.0  0  4  4
2  3  6  5  6  1  1.5  1  9  9