删除熊猫框架中其他形状的行

时间:2018-12-11 23:04:09

标签: python pandas

我正在尝试删除熊猫数据框中的“ MEL”列中形状不同于(99,13)的行。

path    MEL  word
0   8d37d10e7f97ddea2eca9d39a4cf821b4457b041.wav    [[-10.160675, -13.804866, 0.9188097, 4.415375,...   one
1   9a8f761be3fa0d0a963f5612ba73e68cc0ad11ba.wav    [[-10.482644, -13.339122, -3.4994812, -5.29343...   one
2   314cdc39f628bc68d216498b2080bcc7a549a45f.wav    [[-11.076196, -13.980294, -17.289637, -41.0668...   one
3   cc499e63eee4a3bcca48b5b452df04990df83570.wav    [[-13.830213, -12.64104, -3.7780707, -10.76490...   one
4   38cdcc4d9432ce4a2fe63e0998dbca91e64b954a.wav    [[-11.967776, -23.27864, -10.3656, -8.786977, ...   one

我尝试了以下操作:

indexNames = merged[ merged['MEL'].shape != (99,13) ].index
merged.drop(indexNames , inplace=True)

但是第一行代码给了我key error: True。任何人都知道如何实现这一目标?

3 个答案:

答案 0 :(得分:1)

条件

 merged['MEL'].shape != (99,13)

评估为True或False。

请注意,您可以使用布尔矢量选择一个数据框中的行,该布尔矢量的长度与该数据框的索引相同(例如,从数据框的某一列派生而来)。此处更多内容:https://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing

编辑:此代码可能有帮助

 # generate sample dataset
    df = pd.DataFrame(data = {'col1': [np.random.rand(3,2),np.random.rand(5,2),np.random.rand(7,8),np.random.rand(5,2)], 
                              'col2': ['b','a','b','q'],
                              'col3': ['c','c','c','q'],
                              'col4': ['d','d','d','q'], 
                              'col5': ['e','e','a','q'] })

    for index in df.index:
        if df.loc[index]['col1'].shape !=(5,2):
            df.drop(index , inplace=True)

EDIT2:无循环:

df = pd.DataFrame(data = {'col1': [np.random.rand(3,2),np.random.rand(5,2),np.random.rand(7,8),np.random.rand(5,2)], 
                          'col2': ['b','a','b','q'],
                          'col3': ['c','c','c','q'],
                          'col4': ['d','d','d','q'], 
                          'col5': ['e','e','a','q'] })
df['shapes'] = [x.shape for x in df.col1.values]
df = df[df['shapes']!=(5,2)].drop('shapes', axis = 1)

答案 1 :(得分:0)

...换句话说,您希望列'MEL'的形状为(99, 13)的所有行。我会的

my_desired_df = merged[merged['MEL'].shape == (99,13)]

答案 2 :(得分:0)

您需要获取一系列形状

df['MEL'].apply(lambda x: x.shape)

然后您可以测试一下以获取布尔系列

df['MEL'].apply(lambda x: x.shape) == (93,3)

然后使用布尔序列进行索引

new_df = df.loc[df['MEL'].apply(lambda x: x.shape) == (93,3), :]

这将为您提供符合您的形状的一切。这样做可能比使用df.drop()更容易,但是您可以使用

correct = df['MEL'].apply(lambda x: x.shape) == (93,3)
new_df = df.drop(correct[~correct].index)
相关问题