【问题标题】:Filling multiple columns in dataframe填充数据框中的多列
【发布时间】:2020-04-27 10:13:22
【问题描述】:

我有一个现有的数据框df

df
                        KI       Date  
DateTime                                            
2019-12-01 01:00:00    42       2019-12-01
2019-12-01 02:00:00    42       2019-12-01

我想在创建新列时将下表添加到上述数据框中:

[[1, 2],[3, 4]]

最终答案如下所示

df
                        KI       Date       col1    col2
DateTime                                            
2019-12-01 01:00:00    42       2019-12-01  1       2
2019-12-01 02:00:00    42       2019-12-01  3       4

我不知道如何处理这个问题。

编辑:

[[1, 2],[3, 4]] is of type numpy.ndarray

【问题讨论】:

  • [[1, 2],[3, 4]] listdataframenumpy?

标签: pandas python-3.5


【解决方案1】:

试试:

x=[[1,2], [3,4]]

pd.concat([df, pd.DataFrame(data=x, columns=["a", "b"])], axis=1, sort=True)

(将ab 替换为您想要的列名)

【讨论】:

  • TypeError: concat() got an unexpected keyword argument 'sort'
  • @Zanam 升级你的熊猫,你正在使用一个古老的版本。最新的是 0.25
【解决方案2】:

你只需要pd.DataFrame

my_array = np.array([[1, 2],[3, 4]])
df[['col1','col2']] = pd.DataFrame(index=df.index,data = my_array)

                     KI        Date  col1  col2
DateTime                                       
2019-12-01_01:00:00  42  2019-12-01     1     2
2019-12-01_02:00:00  42  2019-12-01     3     4

【讨论】:

    猜你喜欢
    • 2021-03-17
    • 1970-01-01
    • 2023-03-14
    • 2017-04-14
    • 1970-01-01
    • 2021-07-25
    • 2018-01-29
    • 2020-08-30
    • 1970-01-01
    相关资源
    最近更新 更多