【发布时间】:2018-03-20 12:47:53
【问题描述】:
基于此answer 我想编写一个函数将csv 加载到OrderedDict() 中,但我不知道如何解决将键列名称作为字符串传递而不是手动声明它?这是我的代码,它会更清楚:
dic_key = 'uniqueID'
df.dic_key #this gives AttributeError: 'DataFrame' object has no attribute 'dic_key'
而不是df.uniqueID,其中uniqueID 是我们想要将其用作键的列的名称
这里是完整的代码:
def csv_to_OrderedDic1(path, dic_key='uniqueID'):
'''
Parameters:
dic_key: the name of the column to be used as the dictionary key
'''
df = pd.DataFrame.from_csv(path, sep='\t', header=0)
# Get an unordered dictionary
unordered_dict = df.set_index(dic_key).T.to_dict('list')
# Then order it
ordered_dict = OrderedDict((k,unordered_dict.get(k)) for k in df.dic_key)
return ordered_dict
【问题讨论】:
标签: python pandas dictionary dataframe ordereddictionary