`from_dict` 方法返回 TypeError。

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

Pandas from_dict Returns TypeError

问题

我有一个像下面这样的字典:

testProps = {"Key1":[],
             "Key2":False,
             "Key3":True,
             "Key4":[],
             "Key5":False}

我想将它转换为一个 Pandas DataFrame,使用以下代码:

newTestProps = pd.DataFrame.from_dict(testProps, orient="index")

但它抛出了以下错误:

TypeError: object of type 'bool' has no len()

然而,它应该创建一个如下所示的 DataFrame:

`from_dict` 方法返回 TypeError。

这很奇怪,因为我在我的程序中已经有这两行代码很长时间了,直到现在才抛出这个错误。是否可能是 Pandas 存在 bug?

英文:

I have a dictionary like the following:

testProps = {"Key1":[],
             "Key2":False,
             "Key3":True,
             "Key4":[],
             "Key5":False}

I want to convert it to a Pandas DataFrame with

newTestProps = pd.DataFrame.from_dict(testProps,orient="index")

but it is throwing me the following error.

TypeError: object of type 'bool' has no len()

When it should be creating a DataFrame like the following:

`from_dict` 方法返回 TypeError。

Which is bizarre because I've had these two lines of code in my program for a long time and it hasn't thrown this error until now. Is it possible that there's a bug with Pandas?

答案1

得分: 3

创建数据框可以使用以下示例代码:

testProps = {"Key1": [], "Key2": False, "Key3": True, "Key4": [], "Key5": False}

df = pd.DataFrame({'索引': testProps.keys(), 0: testProps.values()})
print(df)

打印结果:

  索引      0
0  Key1     []
1  Key2  False
2  Key3   True
3  Key4     []
4  Key5  False

请注意,我已经将 HTML 编码的引号替换为标准引号以使代码更易于阅读。

英文:

To create the dataframe you can use next example:

testProps = {"Key1": [], "Key2": False, "Key3": True, "Key4": [], "Key5": False}

df = pd.DataFrame({'Index': testProps.keys(), 0: testProps.values()})
print(df)

Prints:

  Index      0
0  Key1     []
1  Key2  False
2  Key3   True
3  Key4     []
4  Key5  False

答案2

得分: 1

我希望这会对你有所帮助

newTestProps = pd.DataFrame(list(zip(testProps.keys(), testProps.values())), columns=['index', 0])

print(newTestProps)

 index   0

0 Key1 []
1 Key2 False
2 Key3 True
3 Key4 []
4 Key5 False

英文:

I hope this will help you

newTestProps = pd.DataFrame(list(zip(testProps.keys(), testProps.values())), columns=['index', 0])


print(newTestProps)



     index   0
0  Key1     []
1  Key2     False
2  Key3     True
3  Key4     []
4  Key5    False

答案3

得分: 1

以下是您要的中文翻译部分:

import pandas as pd

testProps = {"Key1": [], "Key2": False, "Key3": True, "Key4": [], "Key5": False}

df = pd.DataFrame(data=testProps.items(), columns=['索引', '0'])

print(df)
英文:

one of ways you can do it as ,

import pandas as pd

testProps = {"Key1": [], "Key2": False, "Key3": True, "Key4": [], "Key5": False}
  
df = pd.DataFrame(data=testProps.items(), columns=['index','0'])

print(df)

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

发表评论

匿名网友

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

确定