简体   繁体   English

如何将熊猫数据框作为arg传递并对其进行操作?

[英]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 . 您可以尝试使用df.columns而不是您编写的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 . 因此,进行reversed操作是没有意义的。
  2. If you need to maintain order, you need OrderedDict in Python. 如果需要维护订单,则需要使用Python中的OrderedDict
  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]) . 您可以这样做: dict(df[keyname]) (I would call keyname keynames , but thats ust me. You can call it whatever you want.) (我会称呼keyname keynames ,但这是必需的。您可以随意命名。)

Because you indeed have a type error. 因为您确实有类型错误。 You should access to df.columns.values not df.columns.value . 您应该访问df.columns.values而不是df.columns.value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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