【问题标题】:Pandas how to place an array in a single dataframe cell?Pandas 如何将数组放置在单个数据框单元格中?
【发布时间】:2018-12-15 12:58:17
【问题描述】:

所以我目前有一个看起来像这样的数据框:

我想添加一个名为“预测器”的全新列,其中只有一个包含数组的单元格。

所以 [0, 'Predictors'] 应该包含一个数组,并且同一列中该单元格下方的所有内容都应该为空。

这是我的尝试,我尝试创建一个仅包含“预测器”列的单独数据框,并尝试将其附加到当前数据框,但我得到:'长度不匹配:预期轴有 3 个元素,新值有 4元素。'

如何将包含数组的单个单元格附加到我的数据框?

# create a list and dataframe to hold the names of predictors
dataframe=dataframe.drop(['price','Date'],axis=1)  
predictorsList = dataframe.columns.get_values().tolist()
predictorsList = np.array(predictorsList, dtype=object)

# Combine actual and forecasted lists to one dataframe
combinedResults = pd.DataFrame({'Actual': actual, 'Forecasted': forecasted})

predictorsDF = pd.DataFrame({'Predictors': [predictorsList]})

# Add Predictors to dataframe
#combinedResults.at[0, 'Predictors'] = predictorsList
pd.concat([combinedResults,predictorsDF], ignore_index=True, axis=1)

【问题讨论】:

  • (1) Pandas 并非设计用于处理数组项。将数组作为项目是一个坏主意。 (2) Pandas 中没有 empty 单元格之类的东西。每个单元格都必须有一个值。 (3) 为什么不将预测变量保留在自己的变量中?
  • Pandas“单元格”中的列表可能有点棘手,因为它们会导致意外广播。在分配值时添加非广播调用,例如,list(list_variable) 可以通过阻止广播来帮助解决这个问题。显然,这只能在不需要广播时使用。

标签: python pandas dataframe statistics data-science


【解决方案1】:

您可以用NaN 填充所需列中的其余单元格,但它们不会“空”。为此,请在两个索引上使用 pd.merge

设置

import pandas as pd
import numpy as np

df = pd.DataFrame({
     'Actual': [18.442, 15.4233, 20.6217, 16.7, 18.185], 
     'Forecasted': [19.6377, 13.1665, 19.3992, 17.4557, 14.0053]
})

arr = np.zeros(3)
df_arr = pd.DataFrame({'Predictors': [arr]})

合并 df 和 df_arr

result = pd.merge(
    df,
    df_arr,
    how='left',
    left_index=True, # Merge on both indexes, since right only has 0...
    right_index=True # all the other rows will be NaN
)

结果

>>> print(result)
    Actual  Forecasted       Predictors
0  18.4420     19.6377  [0.0, 0.0, 0.0]
1  15.4233     13.1665              NaN
2  20.6217     19.3992              NaN
3  16.7000     17.4557              NaN
4  18.1850     14.0053              NaN

>>> result.loc[0, 'Predictors']
array([0., 0., 0.])

>>> result.loc[1, 'Predictors'] # actually contains a NaN value
nan 

【讨论】:

    【解决方案2】:

    您需要先更改列的对象类型(在您的情况下为Predictors

    import pandas as pd
    import numpy as np
    
    
    df=pd.DataFrame(np.arange(20).reshape(5,4), columns=list('abcd'))
    df=df.astype(object)  # this line allows the signment of the array
    df.iloc[1,2] = np.array([99,99,99])
    print(df)
    

    给予

        a   b             c   d
    0   0   1             2   3
    1   4   5  [99, 99, 99]   7
    2   8   9            10  11
    3  12  13            14  15
    4  16  17            18  19
    

    【讨论】:

      猜你喜欢
      • 2018-08-13
      • 2016-08-24
      • 2021-08-08
      • 2019-08-06
      • 1970-01-01
      • 2014-10-08
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      相关资源
      最近更新 更多