应用elementwise,将结果行连接到DataFram中

2024-10-01 05:06:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个值的列表(很容易变成一个序列或数据帧),我想在上面应用一个函数元素。在

x = [1, 5, 14, 27]

函数本身返回一个DataFrame的单行(返回原始值x和两个结果值列),我希望以一个DataFrame结束。在

^{pr2}$

简单的方法是在列表上执行for循环,并用df.append()对结果进行行绑定,但我确信有一种方法可以用.apply()函数家族来实现这一点。我就是不知道该用哪个。我非常熟悉在R中做这类事情,也熟悉Python,只需要了解一下pandas语法。在

编辑:为了清晰起见,更具体的例子

示例函数:

def returnsquares(x):
    return pd.DataFrame({"input": [x], "sq": x**2, "cube": x**3})

函数的输入是标量,输出是具有单行(不是序列)的数据帧。在

有效代码:

result = pd.DataFrame({}, columns=["input", "sq", "cube"])
for entry in x:
    result = result.append(returnsquares(entry))

(输出值显然与上述值不同,但形状相同)。有更好的方法吗?在


Tags: 数据方法函数dataframe列表forinputsq
1条回答
网友
1楼 · 发布于 2024-10-01 05:06:30

考虑下面的函数,它返回与示例中显示的相同的内容

def special_function(x):
    idx = ['x', 'Val1', 'Val2']
    d = {
         1: pd.Series([x, 4, 23], idx),
         5: pd.Series([x, 56, 27], idx),
        14: pd.Series([x, 10, 9], idx),
        27: pd.Series([x, 8, 33], idx),
    }
    return d[x]

然后使用pd.DataFrame.from_records组合成一个数据帧

^{pr2}$

enter image description here

或使用pd.concat

pd.concat([special_function(i) for i in x])

或者生成x系列并使用apply

x = pd.Series([1, 5, 14, 27])
x.apply(lambda y: special_function(y).iloc[0], 1)

注意时间安排
计时
不要害怕清单的理解

enter image description here

enter image description here

相关问题 更多 >