熊猫:从列中获取值

时间:2021-07-21 13:07:04

标签: python pandas dataframe

我在熊猫中有以下数据框:

dplyr::mutate

如何将其转换为以列作为键和列的值作为值的字典。例如:

transform(eg, Total_Cost = (price * Quantity + fixed_cost1 + fixed_cost2) * Month)
#     type price fixed_cost1 fixed_cost2 Quantity Month Total_Cost
# 1    AAA   0.5         500         200      400     1        900
# 1.1  AAA   0.5         500         200      400     2       1800
# 1.2  AAA   0.5         500         200      400     3       2700
# 1.3  AAA   0.5         500         200      700     1       1050
# 1.4  AAA   0.5         500         200      700     2       2100
# 1.5  AAA   0.5         500         200      700     3       3150
# 2    BBB   0.7         500         200      400     1        980
# 2.1  BBB   0.7         500         200      400     2       1960
# 2.2  BBB   0.7         500         200      400     3       2940
# 2.3  BBB   0.7         500         200      700     1       1190
# 2.4  BBB   0.7         500         200      700     2       2380
# 2.5  BBB   0.7         500         200      700     3       3570
# 3    CCC   0.2         500         200      400     1        780
# 3.1  CCC   0.2         500         200      400     2       1560
# 3.2  CCC   0.2         500         200      400     3       2340
# 3.3  CCC   0.2         500         200      700     1        840
# 3.4  CCC   0.2         500         200      700     2       1680
# 3.5  CCC   0.2         500         200      700     3       2520

1 个答案:

答案 0 :(得分:2)

您可以将 df.to_dict 与 orient='records' 一起使用:

df.to_dict(orient='records')

这将为您提供一个字典列表,每行一个。顺便说一句,您在问题中提供的结构无效,它必须是字典列表或带有键值对的字典