user3107977
user3107977

Reputation: 43

dataframe from dict resulting in empty dataframe

Hi I wrote some code that builds a default dictionary

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)

The dictionary looks good but when I try to convert to dataframe it is empty. I can't figure it out

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: []
{}

Upvotes: 0

Views: 2006

Answers (3)

Isaac
Isaac

Reputation: 1536

You can either pass a list of dicts simply using pd.DataFrame(list_of_dicts) (use pd.DataFrame([dict]) if your variable is not a list) or a dict of list using pd.DataFrame.from_dict(dict). In this last case dict should be something like dict = {a:[1,2,3], "b": ["a", "b", "c"], "c":...}.

see: Pandas Dataframe from dict with empty list value

Upvotes: 0

AirSquid
AirSquid

Reputation: 11913

I think part of your issue is that you are using the keyword 'dict', assuming it is a variable

make a dictionary in your function, call it something other than 'dict'. Have your function return that dictionary. Then when you make a dataframe use that return value. Right now, you are creating a data frame from an empty dictionary object.

Upvotes: 1

jhurst5
jhurst5

Reputation: 77

df = pd.DataFrame(dict)

This should make a dataframe from the dictionary.

Upvotes: 0

Related Questions