【问题标题】:Populating a dictionary of lists with values from 2 columns of a DataFrame使用来自 DataFrame 的 2 列的值填充列表字典
【发布时间】:2021-12-02 09:06:23
【问题描述】:

如果我有一个 DataFrame 存储来自 CSV 文件的 2 列(A 和 B)的值,我将如何使用 for 循环填充字典以从 DataFrame 中获取值?

我需要像这样存储 A B 对的行.. A_&_B_sets = {1:[A1,B1],2:[A2,B2],…}

A_&_B_sets = {1:[A1,B1],2:[A2,B2],…}
for i in (1,n+1):
  A_&_B_sets[i] = i * I

我很迷茫。非常感谢任何帮助。

【问题讨论】:

    标签: python list dictionary for-loop


    【解决方案1】:

    如果你有这样的df

       Column A  Column B
    0         1         4
    1         2         5
    2         3         6
    

    那么你可以这样做:

    A_and_B_sets = {}
    for i, (_, row) in enumerate(df.iterrows(), 1):
        A_and_B_sets[i] = [row["Column A"], row["Column B"]]
    
    print(A_and_B_sets)
    

    打印:

    {1: [1, 4], 2: [2, 5], 3: [3, 6]}
    

    【讨论】:

      猜你喜欢
      • 2020-07-30
      • 1970-01-01
      • 2020-08-29
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      • 2019-10-03
      相关资源
      最近更新 更多