【问题标题】:Initialise DataFrame from numpy array with supplementary columns使用补充列从 numpy 数组初始化 DataFrame
【发布时间】:2018-10-29 03:05:36
【问题描述】:

假设我有以下代码:

import pandas as pd
import numpy as np
A = ['red', 'blue']
B = range(2)
C = np.random.random((4,2,2))
import pandas as pd
df = pd.DataFrame({'Color':np.repeat(A,2),'Trial':np.tile(B,2),'V0':C[:,0,0],'V1':C[:,0,1],
                  'V2':C[:,1,0], 'V3':C[:,1,1]})
df

输出以下数据帧

>   Color Trial    V0          V1         V2          V3
> 0 red     0   0.726781    0.549726    0.053999    0.469885
> 1 red     1   0.609131    0.012120    0.587780    0.344290
> 2 blue    0   0.285235    0.491907    0.907871    0.549792
> 3 blue    1   0.646334    0.164288    0.029917    0.181290

如果数组的大小增加,我想避免输入 numpy 数组的每个条目,所以我想出了以下针对更大数组的解决方案

A = ['red', 'blue']
B = range(2)
C = np.random.random((4,2,2))
import pandas as pd
df = pd.DataFrame({'Color':np.repeat(A,2),'Trial':np.tile(B,2)})
_df = pd.DataFrame(C.reshape(4,4)).add_prefix('V')
df = pd.concat([df,_df],axis=1)
df

具有相同的输出。我的问题是,是否有更好的方法来执行此操作,而不涉及为我要包含的每个数组创建数据框然后将它们连接起来?

【问题讨论】:

  • 你想避免哪一步?

标签: python arrays pandas dataframe


【解决方案1】:

不,看起来你的基础已经覆盖了......不过这里有一些清理,使用DataFrame.assign--

pd.DataFrame(C.reshape(4,4)).add_prefix('V')).assign(
    Color=A * len(A), Trial=np.tile(B, len(A))
)

         V0        V1        V2        V3 Color  Trial
0  0.625676  0.201339  0.873423  0.227824   red      0
1  0.202515  0.515637  0.344809  0.958107  blue      1
2  0.040853  0.682505  0.679995  0.104927   red      0
3  0.548399  0.315772  0.081189  0.282158  blue      1

【讨论】:

  • @piRSquared 谢谢!当我看到 Wen 的意思时,我意识到这可能是必要的。
  • 我最终选择了这个,因为它可以让我完成所有列的命名,但两种解决方案都非常好!
【解决方案2】:

来自MultiIndex

pd.DataFrame(data=C.reshape(4,4), index=pd.MultiIndex.from_product([A,B])).add_prefix('V')


              V0        V1        V2        V3
red  0  0.625676  0.201339  0.873423  0.227824
     1  0.202515  0.515637  0.344809  0.958107
blue 0  0.040853  0.682505  0.679995  0.104927
     1  0.548399  0.315772  0.081189  0.282158

【讨论】:

  • 我喜欢你的想法(-:
猜你喜欢
  • 2018-12-04
  • 2011-06-05
  • 2020-12-28
  • 1970-01-01
  • 2011-08-18
  • 2016-12-13
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
相关资源
最近更新 更多