Dmitry F
Dmitry F

Reputation: 11

delete row from one dataframe and append it to another of same number of columns

This seems like a simple question but i can't figure it out how to remove lines from one data frame and add them to another with simple numeric indexing:

do with iter 1, 2, ...
from: --------------
>>> df2 = pd.DataFrame([[5, 6], [7, 8], [9,10]])
>>> df2
   0   1
0  5   6
1  7   8
2  9  10

>>> df = pd.DataFrame()
>>> df
Empty DataFrame
Columns: []
Index: []

to: --------------
>>> df2 = pd.DataFrame([[5, 6]])
>>> df2
   0  1
0  5  6

>>> df = pd.DataFrame([[7, 8], [9,10]])
>>> df
   0   1
0  7   8
1  9  10

Thanks in advance

Upvotes: 1

Views: 964

Answers (2)

Dmitry F
Dmitry F

Reputation: 11

    vrf_set_size = int(nn_srs_inputs.shape[0]/4)
    index_list = nn_srs_inputs.columns.values
    nn_srs_inputs_vrf = pd.DataFrame(nn_srs_inputs.iloc[0:1, :], columns=index_list)
    nn_srs_inputs = nn_srs_inputs.drop([0])
    nn_srs_inputs = nn_srs_inputs.reset_index(drop=True)

    for i in range(vrf_set_size):
        print(nn_srs_inputs)
        print(nn_srs_inputs_vrf)
        n_to_vrf = random.randint(1, nn_srs_inputs.shape[0]-1)
        nn_srs_inputs_vrf = nn_srs_inputs_vrf.append(
            pd.DataFrame(nn_srs_inputs.iloc[n_to_vrf:n_to_vrf+1,:], columns=index_list), ignore_index=True)
        nn_srs_inputs = nn_srs_inputs.drop([n_to_vrf])
        nn_srs_inputs = nn_srs_inputs.reset_index(drop=True)

Upvotes: 0

Meto
Meto

Reputation: 658

rows = data.iloc[0:3, :]    # Select rows from 0 to 3
data = data.drop([0,1,2], axis=0) # delete rows 0 to 3 here axis=0 is for rows
temp = pd.DataFrame(rows, columns=list(...)) #create new df with selected rows
data2.append(temp) # append new df to second df

Hope this helps. Please refer to pandas documentation for more.

https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html

Upvotes: 2

Related Questions