[英]Convert pandas selected columns into a 2D numpy array
我有一个 10 列和 N 行的 pandas dataframe。 我想从我的数据框中提取两列 select 并将它们放入尺寸为(N,2)的 NumPy 二维数组中。 怎么做?
There is a way to convert a dataframe to a numpy array: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html
你可以只 select 你想要的列:
df[['Col1','Col2']].to_numpy()
我将模拟你的问题来回答这个问题
我首先创建一个包含 10 列和 50 行的数据框:
df = pd.DataFrame(np.random.randint(low = 1 , high = 30 , size = (50 ,10)) , columns = ['a' , 'b' ,'c' ,'d' ,'e' ,'f' ,'g' ,'h' ,'i' ,'j'])
现在我将通过从我的 dataframe df 中获取两列来创建一个大小为 (50,2) 的 numpy 数组:
a = np.array(df[['a' ,'b']])
现在检查 numpy 阵列“a”的形状以确认您的解决方案:
a.shape
上述代码的 output 将为 (50,2)
快乐编码:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.