【问题标题】:Python Pandas Create DataframePython Pandas 创建数据框
【发布时间】:2018-12-01 12:11:16
【问题描述】:

我有一个使用标签然后单热编码的代码。之后,我们将创建一个 DataFrame。还有其他方法可以简单地创建列名,但我只是想了解下面这些代码。 new_poke_df 是现有的数据帧,我们只是将这个数据帧与我们使用 one-hot 编码创建的新功能连接起来。这些新功能是; new_gen_features,new_leg_features。

  1. 我通常将 sum 用于数值,但在这里它与字符串标签一起使用。本例中 Sum() 函数的原因和作用是什么
  2. 末尾还有两个方括号。是什么原因?

如果有人想知道整个代码,我还将链接添加到我的 github(https://github.com/ibozkurt79/practical-machine-learning-with-python/blob/master/notebooks/Ch04_Feature_Engineering_and_Selection/Feature%20Engineering%20on%20Categorical%20Data.ipynb)

new_poke_ohe = pd.concat([new_poke_df, new_gen_features, new_leg_features], 
axis=1)    
columns = sum([['Name', 'Generation', 'Gen_Label'], 
           gen_feature_labels,
           ['Legendary', 'Lgnd_Label'], leg_feature_labels], [])    
new_poke_ohe[columns]

【问题讨论】:

    标签: python dataframe sum


    【解决方案1】:

    sum(list_of_list, []) 是一种扁平化列表列表的 Python 方法。

    看这个例子:

    list_of_list = [['A','B','C'],['D'],['E','F','G','H']]
    sum(list_of_list, [])
    

    输出:

    ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
    

    请注意,您的二维数组(列表列表)现在是一维列表。

    [] 告诉 sum 要添加的起始对象是空的 列表。 quoted from @piRSquared

    因此,这里发生的情况是,您正在从 pd.concat 中数据帧的各种较小的列列表中构建一个新的列列表。

    【讨论】:

      猜你喜欢
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 2021-12-02
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 2020-04-19
      相关资源
      最近更新 更多