如何向DataFrame添加零数组列

huangapple go评论57阅读模式
英文:

How to add column to df with zero array

问题

我想要将一个新的大小为20 x 20的零数组列添加到现有的数据框中。

我尝试过以下代码:

df['matrix'] = np.zeros((20, 20))

但收到了错误信息:

ValueError: Length of values (20) does not match length of index (26651)

看起来它试图将一个单独的零矩阵附加到该列,而不是使每个条目在新列中都是零矩阵。

如果我没有正确格式化问题,对此不熟悉,我深感抱歉。

英文:

I would like to add a new column of zero arrays size 20 x 20 to an existing df.

I tried

df['matrix']= np.zeros((20,20))

received error

ValueError: Length of values (20) does not match length of index (26651)

It seems like it is trying to append a single zero matrix to the column as opposed to having each entry in a new column be a zero matrix.

Apologies if I didn't format the question correctly, I am new to this site.

答案1

得分: 0

Pandas尝试广播numpy数组以适应数据框,但在这种情况下并不有用。

为了避免这种情况,您可以制作一个数组列表。

df["matrix"] = [np.zeros((20, 20)) for _ in df.index]

或者使用apply来获取每个单元格中所需的值。

df["matrix"] = df.apply(lambda _: np.zeros((20, 20)), axis=1)
英文:

Pandas tries to broadcast the numpy array to fit your dataframe in ways that are not helpful in this case.

To avoid this you could make a list of the arrays.

df["matrix"] = [np.zeros((20,20)) for _ in df.index]

Or use apply to get the value you want in each cell

df["matrix"] = df.apply(lambda _: np.zeros((20, 20)), axis=1)

答案2

得分: 0

如果您想要单独的一列,我建议添加一个包含所需信息的 pd.Series,例如:

df['matrix'] = [[0]*20] * len(df)

英文:

If you want a single column I would suggest adding a pd.Series with the desired information, such as:

df['matrix'] = [[0]*20] * len(df)

huangapple
  • 本文由 发表于 2023年6月11日 23:37:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76451204.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定