Python 将数据帧行转换为dict

Python 将数据帧行转换为dict,python,pandas,dictionary,Python,Pandas,Dictionary,我有数据帧,如下面的示例数据。我正在尝试将数据帧中的一行转换为dict,如下面所需的输出。但是当我使用dict时,我会得到索引和列值。是否有人知道如何将行转换为所需输出的dict?非常感谢任何提示 Sample data: print(catStr_df[['Bottle Volume (ml)', 'Pack']][:5]) Bottle Volume (ml) Pack 595 750 12 1889

我有数据帧,如下面的示例数据。我正在尝试将数据帧中的一行转换为dict,如下面所需的输出。但是当我使用dict时,我会得到索引和列值。是否有人知道如何将行转换为所需输出的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}
尝试将
.to_dict('records')[0]
添加到所需的行中

catStr_df[catStr_df['Item Number']==34881].to_dict('records')[0]

采取不同的策略,这是可行的,但您需要获得列列表。这假设您希望索引号作为dict项

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)

@谢谢你这么快回复我。当我尝试添加[0]时,我得到“KeyError:0”。更新:如果我把你的建议拿出来,你的建议非常有效,再次感谢你!努力去理解为什么这有4票。它执行的操作与
T.squere
完全相同,只是这里的[0]看起来很粗糙。@coldspeed,因为它返回一个dict。
T.squere
不将行转换为dict。