gpt4 book ai didi

python - 使用补充列从 numpy 数组初始化 DataFrame

转载 作者:太空宇宙 更新时间:2023-11-03 13:28:58 25 4
gpt4 key购买 nike

假设我有以下代码:

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

具有相同的输出。我的问题是,是否有更好的方法可以做到这一点,而不涉及为我想要包含的每个数组创建一个数据框,然后将它们连接起来?

最佳答案

不,看起来你已经涵盖了你的基础......不过这里有一些清理,使用 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

关于python - 使用补充列从 numpy 数组初始化 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50415280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com