【问题标题】:Dictionary from Pandas dataframe来自 Pandas 数据框的字典
【发布时间】:2018-05-04 15:46:59
【问题描述】:

我使用 pandas read_csv(第一行是标题)读取了一个大文件(1000 万行)的两列,现在我想将数据帧转换为一个字典,其中第一列是键,第二列是价值。

col_name = ['A', 'B']; 
df = pd.read_csv(f_loc, usecols = col_name, sep = "\s+", dtype={'B':np.float16});

【问题讨论】:

    标签: python-2.7 pandas dictionary


    【解决方案1】:

    使用set_index 的第一个column 创建index 并通过Series.to_dict 进行转换:

    df = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B'])
    print (df)
       a  b
    0  1  2
    1  3  4
    
    df = df.set_index('A')['B'].to_dict()
    print (df)
    {1: 2, 3: 4}
    

    zip 的另一个想法:

    d = dict(zip(df['A'], df['B']))
    print (d)
    {1: 2, 3: 4}
    

    或者:

    d = dict(df.values)
    print (d)
    {1: 2, 3: 4}
    

    【讨论】:

      猜你喜欢
      • 2016-02-10
      • 2014-09-28
      • 2018-11-17
      • 1970-01-01
      • 2015-05-30
      • 2019-02-23
      • 2018-12-11
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多