[英]How to convert a python list to pandas Dataframe in python
I have this python
list
and I need to convert it into pandas
dataframe
.我有这个python
list
,我需要将其转换为pandas
dataframe
。
This is how my list looks like:这是我的列表的样子:
thisdict = {}
thisdict["Column1"] = 1
thisdict["Column2"] = 2
thisdict # this print
{'Column1': 1, 'Column2': 2}
And I need to convert this to pandas
dataframe.我需要将其转换为pandas
dataframe。
I tried:我试过了:
df = pd.DataFrame(thisdict)
and I got the error as below:我得到如下错误:
ValueError: If using all scalar values, you must pass an index ValueError:如果使用所有标量值,则必须传递索引
Can someone please help me?有人可以帮帮我吗?
You are supposed to assign the column as lists in your code.您应该将该列分配为代码中的列表。
Try replacing lines 2 and 3 with:尝试将第 2 行和第 3 行替换为:
thisdict["Column1"] = [1]
thisdict["Column2"] = [2]
Complete code:完整代码:
thisdict = {}
thisdict["Column1"] = [1]
thisdict["Column2"] = [2]
df = pd.DataFrame(thisdict)
Output: Output:
Column1 Column2
0 1 2
If for some reason you didn't want to make your columns as lists, you could do this.如果由于某种原因您不想将列设置为列表,您可以这样做。
df = pd.DataFrame(pd.Series(thisdict)).transpose()
If your dictionary is going to one row of a dataframe you need to pass in a list with a single element.如果您的字典将转到 dataframe 的一行,则您需要传入一个包含单个元素的列表。
pd.DataFrame(thisdict, index=[0])
Output: Output:
Column1 Column2
0 1 2
It's not clear from your question what you want, but here are a couple options;从您的问题中不清楚您想要什么,但这里有几个选项; I think you probably want the second option.我想你可能想要第二种选择。 To achieve it, make sure you use a list when you build your dictionary.要实现它,请确保在构建字典时使用列表。
Option-1选项1
thisdict = {}
thisdict["Column1"] = 1
thisdict["Column2"] = 2
print(thisdict)
print("Below is Option1:")
df = pd.DataFrame(list(thisdict.items()),columns = ['ColumnA','ColumnB'])
display(df)
Option-2选项 2
thisdict = {}
thisdict["Column1"] = [1]
thisdict["Column2"] = [2]
print(thisdict)
print("Below is Option2:")
df = pd.DataFrame(thisdict)
display(df)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.