简体   繁体   English

具有变量组合(或排列)并分配给数据框的函数值

[英]Function Value with Combination(or Permutation) of Variables and Assign to Dataframe

I have n variables.我有n变量。 Suppose n equals 3 in this case.假设在这种情况下n等于 3。 I want to apply one function to all of the combinations(or permutations, depending on how you want to solve this) of variables and store the result in the same row and column in dataframe.我想将一个函数应用于变量的所有组合(或排列,取决于您想如何解决这个问题),并将结果存储在数据框中的同一行和列中。

a = 1
b = 2
c = 3
indexes = ['a', 'b', 'c']
df = pd.DataFrame({x:np.nan for x in indexes}, index=indexes)

If I apply sum(the function can be anything), then the result that I want to get is like this:如果我应用 sum(函数可以是任何东西),那么我想要得到的结果是这样的:

    a   b   c
a   2   3   4
b   3   4   5
c   4   5   6

I can only think of iterating all the variables, apply the function one by one, and use the index of the iterators to set the value in the dataframe.我只能想到迭代所有变量,将函数一一应用,并使用迭代器的索引来设置数据帧中的值。 Is there any better solution?有没有更好的解决办法?

You can use apply and return a pd.Series for that effect.您可以使用 apply 并返回pd.Series以获得该效果。 In such cases, pandas uses the series indices as columns in the resulting dataframe.在这种情况下, pandas使用系列索引作为结果数据框中的列。

s = pd.Series({"a": 1, "b": 2, "c": 3})
s.apply(lambda x: x+s) 

Just note that the operation you do is between an element and a series.请注意,您所做的操作是在元素和系列之间进行的。

I believe you need broadcast sum of array created from variables if performance is important:如果性能很重要,我相信您需要广播从变量创建的数组总和:

a = 1
b = 2
c = 3
indexes = ['a', 'b', 'c']

arr = np.array([a,b,c])
df =  pd.DataFrame(arr + arr[:, None], index=indexes, columns=indexes)
print (df)
   a  b  c
a  2  3  4
b  3  4  5
c  4  5  6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM