【问题标题】:Pandas dataframe conversion to numpy array returns unexpected shapePandas 数据框转换为 numpy 数组返回意外的形状
【发布时间】:2020-10-03 14:05:20
【问题描述】:

我的问题是,当我将列转换为 numpy 数组时,我不明白为什么 pandas/numpy 返回某个数组形状。我希望 shape 是 (1440, 130, 13) 但由于当我调用 @987654324 时我得到一个 np.array 的“列表调用”(字面上不知道为什么) @ 在我的数据框列上,我得到了 (1440, ) 的 shape

起初我以为我存储数据帧的文件类型可能是问题(我之前尝试过 json 和 csv),但我对它们中的任何一个都有同样的问题。

非常感谢!

def extract_features(data_df):

    mfcc_list = []

    for i in tqdm(range(len(data_df))):
        signal, sr = librosa.load(data_df.path[i], sr=SAMPLE_RATE, duration=3)

        mfcc = librosa.feature.mfcc(signal, sr=sr, n_mfcc=13, n_fft=2048, hop_length=512)
        mfcc = mfcc.T

        mfcc_list.append(mfcc.tolist()) # I make sure that everything is in list form

    data_df['mfcc'] = mfcc_list
    return data_df
data_df = extract_features(data_df=data_df)
data_df.to_pickle('path/to/file')
df = pd.read_pickle('path/to/file')

a = df["mfcc"].to_numpy() # I would expect a shape of (1440, 130, 13)

b = np.array(df.iloc[0]["mfcc"])

print(a)
# output in a shape like this:
# [list([[], ..., []]), ..., list([[], ..., []])]

print(type(a))    # output: <class 'numpy.ndarray'>
print(type(a[0])) # output: <class 'list'>

print(type(b))    # output: <class 'numpy.ndarray'>
print(type(b[0])) # output: <class 'numpy.ndarray'>
df.info()
# output:
# <class 'pandas.core.frame.DataFrame'>
# Int64Index: 1440 entries, 0 to 1439
# Data columns (total 9 columns):
#  #   Column      Non-Null Count  Dtype 
# ---  ------      --------------  ----- 
#  0   path        1440 non-null   object
#  1   source      1440 non-null   object
#  2   actor       1440 non-null   object
#  3   gender      1440 non-null   object
#  4   statement   1440 non-null   object
#  5   repetition  1440 non-null   object
#  6   intensity   1440 non-null   object
#  7   emotion     1440 non-null   object
#  8   mfcc        1440 non-null   object
# dtypes: object(9)
# memory usage: 112.5+ KB

print(df.shape) # output: (1440, 9)

df["mfcc"]
# output:
# 0       [[-857.3094533443688, 0.0, 0.0, 0.0, 0.0, 0.0,...
# 1       [[-864.8902862773604, 0.0, 0.0, 0.0, 0.0, 0.0,...
# 2       [[-849.4454325616318, 9.397479238778757, 9.257...
# 3       [[-832.7343966188961, 11.492822043371124, 0.14...
# 4       [[-902.4064116162402, 6.517241898027468, 6.427...
#                               ...                        
# 1435    [[-764.9126134873547, 0.0, 0.0, 0.0, 0.0, 0.0,...
# 1436    [[-732.3714481202685, 0.0, 0.0, 0.0, 0.0, 0.0,...
# 1437    [[-741.4161339882342, 0.0, 0.0, 0.0, 0.0, 0.0,...
# 1438    [[-713.4635562123195, 0.0, 0.0, 0.0, 0.0, 0.0,...
# 1439    [[-718.5457158330038, 0.0, 0.0, 0.0, 0.0, 0.0,...
# Name: mfcc, Length: 1440, dtype: object

【问题讨论】:

  • 显示一些df 信息 - dtypes、形状、信息。
  • @hpaulj 我添加了一些附加信息

标签: python arrays pandas numpy dataframe


【解决方案1】:

数据框是一个二维对象。即使我像这样制作一个,它也是二维的,每个“单元格”中都有列表:

In [39]: df = pd.DataFrame({'a':[[1,2,3],[4,5,6],[7,8,9]]})                                                     
In [40]: df                                                                                                     
Out[40]: 
           a
0  [1, 2, 3]
1  [4, 5, 6]
2  [7, 8, 9]
In [41]: df.to_numpy()                                                                                          
Out[41]: 
array([[list([1, 2, 3])],
       [list([4, 5, 6])],
       [list([7, 8, 9])]], dtype=object)

这是包含列表(作为对象)的 (3,1) 数组。如果我选择一列,我会得到一个熊猫系列

In [42]: df['a'].to_numpy()                                                                                     
Out[42]: array([list([1, 2, 3]), list([4, 5, 6]), list([7, 8, 9])], dtype=object)
In [43]: print(_)                                                                                               
[list([1, 2, 3]) list([4, 5, 6]) list([7, 8, 9])]

这是一个一维 (3,) 形状数组,同样包含列表。

如果列表的形状匹配,则可以将stack 合并为一个数组:

In [44]: np.stack(df['a'].to_numpy())                                                                           
Out[44]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

===

“3d”示例:

In [45]: df = pd.DataFrame({'a':[[[1,2],[3,4]],[[4,5],[6,7]]]})                                                 
In [46]: df                                                                                                     
Out[46]: 
                  a
0  [[1, 2], [3, 4]]
1  [[4, 5], [6, 7]]
In [47]: df['a'].to_numpy()                                                                                     
Out[47]: array([list([[1, 2], [3, 4]]), list([[4, 5], [6, 7]])], dtype=object)
In [48]: np.stack(df['a'].to_numpy())                                                                           
Out[48]: 
array([[[1, 2],
        [3, 4]],

       [[4, 5],
        [6, 7]]])
In [49]: _.shape                                                                                                
Out[49]: (2, 2, 2)

【讨论】:

  • 好的,我认为它为我解释了它。我想我当时只是用错了。我的目的是将所有“mfcc”和每个“情感”提取为一个列表,然后将其拆分,以便我可以用它训练一个 ML 模型。我正在建立一个语音情感识别模型。非常感谢您的明确回答!
猜你喜欢
  • 2020-06-20
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 2014-03-23
  • 2021-04-02
相关资源
最近更新 更多