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

时间:2016-12-16 19:37:05

标签: python pandas

我有一个值列表(可以很容易地成为一个Series或DataFrame),我想在其中应用元素元素。

x = [1, 5, 14, 27]

函数本身返回一行DataFrame(返回原始值x和两个结果值列),我想最终得到一个DataFrame。

    x    Val1    Val2
0   1       4      23
1   5      56      27
2  14      10       9
3  27       8      33

简单方法是列表上的for循环,行将结果与df.append()绑定,但我确信有一种方法可以使用.apply()系列功能。我只是想不通确切地使用哪个。我非常熟悉在R中做这类事情,并熟悉Python,只需要了解一下pandas语法。

编辑:更清楚的具体例子

示例功能:

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

函数的输入是标量,输出是具有单行的DataFrame(非一系列)。

有效的代码:

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

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

1 个答案:

答案 0 :(得分:2)

考虑以下函数返回您在示例中显示的相同内容

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

合并为单个数据框
pd.DataFrame.from_records([special_function(i).squeeze() for i in x])

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