嗨,我写了一些代码来构建默认字典
def makedata(filename):
with open(filename, "r") as file:
for x in features:
previous = []
count = 0
for line in file:
var_name = x
regexp = re.compile(var_name + r'.*?([0-9.-]+)')
match = regexp.search(line)
if match and (match.group(1)) != previous:
previous = match.group(1)
count += 1
if count > wlength:
count = 1
target = str(str(count) + x)
dict.setdefault(target, []).append(match.group(1))
file.seek(0)
df = pd.DataFrame.from_dict(dict)
字典看起来不错,但是当我尝试转换为数据框时,它是空的。我不明白
dict:
{'1meanSignalLenght': ['0.5305184', '0.48961428', '0.47203177', '0.5177274'], '1amplCor': ['0.8780955002105448', '0.8634431017504487', '0.9381169983046714', '0.9407036427333355'], '1metr10.angle1': ['0.6439386643584522', '0.6555194964997434', '0.9512436169922103', '0.23789348400794422'], '1syncVar': ['0.1344131181025432', '0.08194580887223515', '0.15922251165913678', '0.28795644612520327'], '1linVelMagn': ['0.07062673289287498', '0.08792496681784517', '0.12603999663935528', '0.14791253129369603'], '1metr6.velSum': ['0.17850601560734558', '0.15855169971072014', '0.21396496345720045', '0.2739525279330513']}
df:
Empty DataFrame
Columns: []
Index: []
{}
答案 0 :(得分:1)
我认为您遇到的问题之一是您假设关键字“ dict”是一个变量
在函数中创建字典,将其称为“ dict”以外的名称。让您的函数返回该字典。然后,当您创建数据框时,请使用该返回值。现在,您正在从一个空的字典对象创建一个数据框。
答案 1 :(得分:0)
df = pd.DataFrame(dict)
这应该从字典中创建一个数据框。
答案 2 :(得分:0)
您可以只使用pd.DataFrame(list_of_dicts)
(如果变量不是列表,则使用pd.DataFrame([dict])
)来传递字典列表,也可以使用pd.DataFrame.from_dict(dict)
来传递列表字典。在后一种情况下,字典应该类似于dict = {a:[1,2,3], "b": ["a", "b", "c"], "c":...}
。