【问题标题】:Convert each element of pandas dataframe into dict将 pandas 数据帧的每个元素转换为 dict
【发布时间】:2021-08-02 19:11:21
【问题描述】:

我正在尝试为 pandas 数据框的每个元素添加特征索引,以便每个元素都类似于 column_number:feature_value。例如,如果输入是这样的:

        col1    col2
row1    1.23    2.24
row2    0.42    5.52

那么,输出数据框应该是这样的:

        col1    col2
row1    1:1.23    2:2.24
row2    1:0.42    2:5.52

这里每个元素的dict的key和value分别是intfloat类型。这是我的代码:

f1 = pd.DataFrame()
# removing the ground truth
X = feature_matrix1.drop(['Disease'], axis=1)
X1 = X.copy()
for i in tqdm(range(X.shape[0])):
    for j in range(X.shape[1]):
        X1.iloc[i,j] = {}
        X1.iloc[i,j][i] = X1.iloc[i,j]

X 的大小为 1235x13160。但我收到Incompatible indexer with Series 的错误。请提出建议。

【问题讨论】:

    标签: python pandas dataframe dictionary


    【解决方案1】:

    我使用以下代码来获得我想要的输出格式:

    f_out = open('check_features.csv','w')
    X = feature_matrix1.drop(['Disease'], axis=1)
    Y = feature_matrix1['Disease'].tolist()
    for i in tqdm(range(X.shape[0])):
        line = ''
        line += str(Y[i]) + '\t'
        for j in range(X.shape[1]):
            line +=  str(j+1) + ':' + str(X.iloc[i,j]) + '\t'
        line += '\n'
        f_out.write(line)
    
    f_out.close()
    

    【讨论】:

      【解决方案2】:

      首先转换为字符串并使用radd得到期望输出:

      >>> df.astype(str).radd([f'{i+1}:' for i in range(len(df.columns))])
      
              col1    col2
      row1  1:1.23  2:2.24
      row2  1:0.42  2:5.52
      

      【讨论】:

      • 是的。我也有同样的期待。感谢您的简短命令。我的方式是传统类型(因为我不是一个好的程序员;))。感谢您的回答,也感谢其他人。
      • 如果有适合您需要的答案,请不要忘记接受。这对其他有类似情况的用户很重要。
      【解决方案3】:

      您可以使用df.columns.get_loc() 获取列整数位置编号(从0 开始),然后将字符串与每列的列值连接起来,如下所示:

      for col in df.columns:
          df[col] = str(df.columns.get_loc(col) + 1) + ':' + df[col].astype(str)
      

      结果:

      print(df)
      
              col1    col2
      row1  1:1.23  2:2.24
      row2  1:0.42  2:5.52
      

      【讨论】:

        【解决方案4】:

        有效

        for c in df.columns:
            df[c] = df[c].apply(lambda x:f"{c[-1]}:{x}")
        

        结果

                col1    col2
        row1  1:1.23  2:2.24
        row2  1:0.42  2:5.52
        

        【讨论】:

          【解决方案5】:

          短版

          [f"{i+1}:" for i in range(df.shape[1])] + df.astype(str)
          

          出来

                  col1    col2
          row1  1:1.23  2:2.24
          row2  1:0.42  2:5.52
          

          【讨论】:

            猜你喜欢
            • 2018-08-14
            • 2015-06-19
            • 2012-04-03
            • 2021-12-18
            • 2017-02-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多