Pandas: Shape of passed values is (10, 1), indices imply (10, 5) error when trying to append a dict to an existing Dataframe

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

Pandas: Shape of passed values is (10, 1), indices imply (10, 5) error when trying to append a dict to an existing Dataframe

问题

mydict = {}
for index, i in enumerate(array):
    mydict[index] = f"{i}"

df_new = pd.concat([df[:3], pd.DataFrame(mydict.values(), columns=['C', 'D', 'E'])], axis=1)

这是您想要的结果:

    A     B     C     D     E
0   aa   bbbb  0.49  0.43  0.06
1  aaa    bb   0.5   0.47  0.02
2    a     bb  0.04  0.34  0.6

这个错误是由于您的DataFrame形状不匹配引起的,您的原始DataFrame有两列('A'和'B'),而您尝试附加的DataFrame有三列('C'、'D'和'E')。我已经修改了代码以匹配您的预期结果。

英文:

Right now I've a DataFrame that looks like this:

    A         B
0   aa       bbbb
1  aaa	      bb
2   a         bb

And an array like this:

[array([0.49, 0.43, 0.06], dtype=float32),
 array([0.5, 0.47 , 0.02], dtype=float32),
 array([0.04, 0.34, 0.6], dtype=float32)]

I'd like to add this value to my original df. So I first converted my array to a dict and then I tried to append it to my original df:

mydict={}
for index, i in enumerate(array):
    mydict[index]=f"{i}"
 df_new = pd.concat([df[:3], pd.DataFrame(mydict.values(), columns=['A', 'B','C','D','E'])], ignore_index=True)

This is what I'd like to achieve:

     A     B      C     D     E
0   aa    bbbb   0.49  0.43  0.06
1  aaa	   bb    0.5   0.47  0.02
2   a      bb    0.04  0.34  0.6

But this is the error I'm getting:

Shape of passed values is (10, 1), indices imply (10, 5)

答案1

得分: 1

准备数据
```python
import numpy as np
import pandas as pd

df = pd.DataFrame({'A': ['aa', 'aaa', 'a'], 'B': ['bbbb', 'bb', 'bb']})

array = [np.array([0.49, 0.43, 0.06], dtype=np.float32), 
 np.array([0.5, 0.47, 0.02], dtype=np.float32), 
 np.array([0.04, 0.34, 0.6], dtype=np.float32)]

你可以直接将数组列表转换为DataFrame,而不必先将其转换为字典再转换为DataFrame。

df2 = pd.DataFrame(array, columns=['C', 'D', 'E'])
pd.concat([df, df2], axis=1)


      A	    B	   C	   D	   E
0	 aa	 bbbb	0.49	0.43	0.06
1	aaa	   bb	0.50	0.47	0.02
2	  a	   bb	0.04	0.34	0.60
英文:

Preparing the data

import numpy as np
import pandas as pd

df = pd.DataFrame({'A': ['aa', 'aaa', 'a'], 'B': ['bbbb', 'bb', 'bb']})

array = [np.array([0.49, 0.43, 0.06], dtype=np.float32), 
 np.array([0.5, 0.47, 0.02], dtype=np.float32), 
 np.array([0.04, 0.34, 0.6], dtype=np.float32)]

You can convert the list of arrays directly to a dataframe, instead of converting it to a dictionary before converting to dataframe.

df2 = pd.DataFrame(array, columns=['C', 'D', 'E'])
pd.concat([df, df2], axis=1)


      A	    B	   C	   D	   E
0	 aa	 bbbb	0.49	0.43	0.06
1	aaa	   bb	0.50	0.47	0.02
2	  a	   bb	0.04	0.34	0.60

huangapple
  • 本文由 发表于 2023年1月6日 10:38:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75026412.html
匿名

发表评论

匿名网友

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

确定