简体   繁体   中英

How can I pass a pandas dataframe as an arg and manipulate it?

I wrote a function to take a dataframe and result a data dictionary for later processing. It seems pretty straightforward, but I get the error:

AttributeError: 'Index' object has no attribute 'value'

def createDataDict(df, keyname):
""" create a dictionary of dictionaries that looks like this:

        { <License_Number> : {<label>:<labelValue>, <feature1>:<feature1Value>, ...}

    for example:
        { 123456: {'violator': False, Total_Sales': 1000, 'violation_count': 2} , ...}

"""

""" for each row in dataframe, pull off license number for key, 
    take each column name and value and add to dictionary
"""
keys = df[keyname]
for key in keys:
    dict = {}
    for col in reversed(list(df.columns.value)):
        feature_values = {}
        feature_values[col] = df[col] 
        dict[key] = feature_values 

You can try df.columns instead of what you have written df.columns.value .

There are also a couple of things to note ...

  1. dictionaries are not ordered. So it is meaningless to do a reversed .
  2. If you need to maintain order, you need OrderedDict in Python.
  3. If you already have the columns that you want to convert, you don't need to write a function. You can just do: dict(df[keyname]) . (I would call keyname keynames , but thats ust me. You can call it whatever you want.)

Because you indeed have a type error. You should access to df.columns.values not df.columns.value .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM