简体   繁体   English

如何将 `numpy.hstack()` 与 `numpy.ndarray` 数据类型一起使用?

[英]How to use `numpy.hstack()` with `numpy.ndarray` data type?

I have a numpy.DataFrame say df with 3 columns, col_1 , col_2 , col_3 .我有一个numpy.DataFramedf有 3 列col_1col_2col_3 Data in col_1 are numpy.ndarray and looks like this: array([ 0.216, -0.290, 0.349]) col_1中的数据是numpy.ndarray ,如下所示: array([ 0.216, -0.290, 0.349])

How could I use np.hstack() to expand the DataFrame with columns consist of each data point in col_1 ?我如何使用 np.hstack() 来扩展DataFrame ,其中列由col_1中的每个数据点组成?

ie Original DataFrame原装DataFrame

                     col_1   col_2               col_3
------------------------------------------------------
0   [0.216, -0.290, 0.349]  NORMAL  N09_M07_F10_K001_1

Supposed DataFrame假设 DataFrame

                 col_3  col_2     0      1     2
------------------------------------------------
0   N09_M07_F10_K001_1 NORMAL 0.216 -0.290 0.349

I'd tried like this:我试过这样:

Supposed_DataFrame = pd.concat(
    [df[['label', 'filename']], 
     pd.DataFrame(np.hstack(df["signal"].values).T)
    ], 
    axis=1)

but the output was:但 output 是:

                 col_3  col_2     0
-----------------------------------
0   N09_M07_F10_K001_1 NORMAL 0.216

any simpler solutions will be appreciated任何更简单的解决方案将不胜感激

Check out this code:看看这段代码:

import pandas as pd

dict_ = {
    'col_1': [[0.216, -0.290, 0.349]],
    'col_2': 'NORMAL',
    'col_3': 'N09_M07_F10_K001_1'
        }
df2 = pd.DataFrame(dict_)

supposed_DataFrame = pd.concat([df2[['col_3', 'col_2']], pd.DataFrame(df2['col_1'].to_list(), columns=[0,1,2])], axis=1)
print (supposed_DataFrame)

Method-2 : using basic steps:方法2 :使用基本步骤:

row_1 = df2['col_1'][0]
for i in range(len(row_1)):
    df2[i] = row_1[i]

df2.drop('col_1', axis=1, inplace=True)

print(df2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM