Ironman10
Ironman10

Reputation: 259

How to append a row to another dataframe

I have dataframes df1 and df2 both with columns ["Ticker", "Adj.Factor", "Date"]. I want to add to df2 the complete row from df1 if the value of "Adj.Factor" in that row in df1 equals to 0.

I have the following code.

for x in range(tot_len):
    if df1.iloc[x]['Adj.Factor'] == 0:
        df2.append(df1.iloc[x])  --> not working.

`

I have tried printing the values and it shows the correct output. But the values are not appended to df2.

Upvotes: 14

Views: 53120

Answers (2)

Mr Tarsa
Mr Tarsa

Reputation: 6652

It seems you missed an assignment. Here is a simpler solution

df2 = df2.append(df1[df1['Adj.Factor'] == 0])

Update since pandas 1.4.0:

pd.DataFrame.append is deprecated now, use pd.concat instead

df2 = pd.concat([df2, df1[df1['Adj.Factor'] == 0]])

Upvotes: 16

Dr. Strangelove
Dr. Strangelove

Reputation: 3328

Try:

df2 = df2.append(df1.iloc[x])

DataFrame.append(self, other, ignore_index=False, verify_integrity=False, sort=False) → 'DataFrame

Append rows of other to the end of caller, returning a new object.

REF

Upvotes: 4

Related Questions