将数据帧行转换为字典

问题描述 投票:0回答:4

我有像下面的示例数据这样的数据帧。 我正在尝试将数据帧中的一行转换为类似于下面所需输出的字典。 但是当我使用 to_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}
python pandas dictionary
4个回答
60
投票

尝试将

.to_dict('records')[0]
添加到您想要的行

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

8
投票

使用

df.to_dict(orient='index')
将索引值作为键,方便检索数据


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)

0
投票
dictionary = df.iloc[row].to_dict()
© www.soinside.com 2019 - 2024. All rights reserved.