我有一个值的列表(很容易变成一个序列或数据帧),我想在上面应用一个函数元素。在
x = [1, 5, 14, 27]
函数本身返回一个DataFrame的单行(返回原始值x
和两个结果值列),我希望以一个DataFrame结束。在
简单的方法是在列表上执行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))
(输出值显然与上述值不同,但形状相同)。有更好的方法吗?在
考虑下面的函数,它返回与示例中显示的相同的内容
然后使用
^{pr2}$pd.DataFrame.from_records
组合成一个数据帧或使用
pd.concat
或者生成
x
系列并使用apply注意时间安排
计时
不要害怕清单的理解
相关问题 更多 >
编程相关推荐