如何在熊猫数据框上进行迭代以为每次迭代获取许多行

时间:2020-07-15 13:00:30

标签: python pandas

我有一个熊猫数据框。

DF.shape = (13096,27)

我要在数据帧上进行迭代,对于每次迭代,我都使用shape of (50, 25)。我的意思是前25列是25列。

我使用以下代码完成了

for i in test_df.iterrows():
        df1 = test_df.iloc[:50, 0:25]
        df1 = np.array(df1)

        seq_test_array = df1[newaxis, :, :]
        print('df1', seq_test_array.shape)

        #a = np.arange(10)
        #for i in np.nditer(seq_test_array):
        predictions = model.predict_classes(seq_test_array,verbose=1, batch_size=50)
        fig_verify = plt.figure(figsize=(5, 5))
        plt.plot(predictions, color="blue")
        plt.plot(predictions, color="green")
        plt.title('prediction')
        plt.ylabel('value')
        plt.xlabel('row')
        plt.show()

        print('predictions', predictions)
        preds = model.predict(seq_test_array)
        print('preds', preds)
        prediction = np.argmax(preds)
        print('prediction', prediction)

我布置了图,但它们是空的。预测值与pred值相同(打印结果):

predictions [[1]]
preds [[0.9416911]]
prediction 0
df1 (1, 50, 25)

是因为我的代码错误吗?

能帮我吗? 谢谢

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

sliced=50  
for i in range(0,len(df)-(sliced-1),sliced):
    subdf=df.iloc[i:i+sliced,df.columns[:-2]]
    ....
    #the rest of your code 

例如,

import numpy as np
import pandas as pd


N_rows=6
N_cols=5
df = pd.DataFrame(np.zeros((N_rows, N_cols)))
print(df)

sliced=2
for i in range(0,len(df)-(sliced-1),sliced):
    subdf=df.iloc[i:i+sliced,df.columns[:-2]]
    print(subdf)
    print(subdf.shape)

输出:

df
     0    1    2    3    4
0  0.0  0.0  0.0  0.0  0.0
1  0.0  0.0  0.0  0.0  0.0
2  0.0  0.0  0.0  0.0  0.0
3  0.0  0.0  0.0  0.0  0.0
4  0.0  0.0  0.0  0.0  0.0
5  0.0  0.0  0.0  0.0  0.0


Iterations:

     0    1    2
0  0.0  0.0  0.0
1  0.0  0.0  0.0
(2, 3)
     0    1    2
2  0.0  0.0  0.0
3  0.0  0.0  0.0
(2, 3)
     0    1    2
4  0.0  0.0  0.0
5  0.0  0.0  0.0
(2, 3)

因此,如您所见,每次迭代都采用(2,3)的形状,表示(sliced, len(df.columns)-2),因此在您的情况下为(50, 25)

相关问题