我有数据框,如下面的示例数据。我正在尝试将数据帧中的一行转换为dict,如下面所需的输出。但是当我使用to_dict时,我得到了indice和列值。有谁知道如何将行转换为dict,如所需的输出?任何提示非常感谢。
Sample data:
print(catStr_df[['Bottle Volume (ml)', 'Pack']][:5])
Bottle Volume (ml) Pack
595 750 12
1889 750 12
3616 1000 12
4422 750 12
5022 750 12
Code:
v = catStr_df[catStr_df['Item Number']==34881][['Bottle Volume (ml)', 'Pack']]\
.drop_duplicates(keep='first').to_dict()
v
Output:
{'Bottle Volume (ml)': {9534: 1000}, 'Pack': {9534: 12}}
Desired output:
{'Bottle Volume (ml)': 1000, 'Pack': 12}
答案 0 :(得分:8)
尝试将.to_dict('records')[0]
添加到您想要的行
catStr_df[catStr_df['Item Number']==34881].to_dict('records')[0]
答案 1 :(得分:0)
采用不同的策略,这可行,但您需要获取列列表。这假设您希望索引号作为字典项
def row_converter(row, listy):
#convert pandas row to a dictionary
#requires a list of columns and a row as a tuple
count = 1
pictionary = {}
pictionary['Index'] = row[0]
for item in listy:
pictionary[item] = row[count]
count += 1
print(pictionary)
return pictionary
df = PD.read_csv("yourFile", dtype=object, delimiter=",", na_filter=False)
listy = df.columns
for row in df.itertuples():
rowDict = row_converter(row, listy)