在数据框列上应用函数以获取其他几个列 Pandas Python
Apply function on dataframe Column to get several other columns Pandas Python
我有一个包含数千行的数据框。我想在单个列上应用一个函数以获得其他 7 列并将其合并到数据框。
数据框示例:
df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6]})
a b
0 1 4
1 2 5
2 3 6
函数示例。函数returns一个数据帧
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
Return 一个 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]
或者,
def function(x):
return pd.Series({'c':x+2,'d':x*2,'e':x%2,'f':x/2,'g':x-2,'h':x**2,'i':x*x})
您需要从 DataFrame
构造函数中删除 []
并处理列 a
中的值,如数组使用 DataFrame.pipe
:
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
我有一个包含数千行的数据框。我想在单个列上应用一个函数以获得其他 7 列并将其合并到数据框。 数据框示例:
df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6]})
a b
0 1 4
1 2 5
2 3 6
函数示例。函数returns一个数据帧
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
Return 一个 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]
或者,
def function(x):
return pd.Series({'c':x+2,'d':x*2,'e':x%2,'f':x/2,'g':x-2,'h':x**2,'i':x*x})
您需要从 DataFrame
构造函数中删除 []
并处理列 a
中的值,如数组使用 DataFrame.pipe
:
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