[英]Python dictionary to dataframe - DataFrame constructor not properly called
I used a dictionary containing source-destination
as keys and messages
as values. 我使用了一个字典,其中包含
source-destination
作为键,而messages
作为值。 It loops over the first dataframe, for each question, store who posted 1st message as the destination, store who posted 2nd message as source, add a counter in dictionary at key 'source-destination'. 它循环遍历第一个数据框,对于每个问题,将第一个消息作为目标存储,将第二个消息作为源存储,在字典中的“源-目标”键处添加一个计数器。
Now I am trying to convert dictionary to dataframe, but I get this error message ValueError: If using all scalar values, you must pass an index
. 现在,我尝试将字典转换为数据帧,但出现以下错误消息
ValueError: If using all scalar values, you must pass an index
。
import pandas as pd
from itertools import permutations
df = pd.read_csv('example.csv', sep=';', engine='python')
messages = {} # the dictionary where results is going to be stored
student= set()
destination = False # a simple boolean to make sure message 2 follows message 1
for row in df: # iterate over the dataframe
student.add(row[2]) # collect students' name
if row[1] == 1: # if it is an initial message
destination = row[2] # we store students as destination
elif row[1] == 2 and destination: # if this is a second message
source = row[2] # store student as source
key = source + "-" + destination # construct a key based on source/destination
if key not in messages: # if the key is new to dictionary
messages[key] = 1 # create the new entry
else: # otherwise
messages[key] += 1 # add a counter to the existing entry
destination = False # reset destination
else:
destination = False # reset destination
# add the pairs of source-destination who didn't interact in the dictionnary
for pair in permutations(student, 2):
if "-".join(pair) not in messages:
messages["-".join(pair)] = 0
f1 = pd.DataFrame.from_dict(messages)
print(f1)
Any idea why? 知道为什么吗?
Thank you in advance. 先感谢您。
May be you have a mix between tab and space in your code. 可能是您的代码中制表符和空格之间存在混淆。 Try to remove all the tabs and replace them with spaces.
尝试删除所有选项卡,并用空格替换它们。
Same problem : IndentationError: unindent does not match any outer indentation level 相同的问题: IndentationError:unindent与任何外部缩进级别都不匹配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.