Add new row at end of pandas dataframe with specific value in all columns

Viewed 2135

I have a dataframe that looks like:

 Col1     Col2  .....    Col48
 078      abc            0.99
 097      def            0.91
 027      xyz            0.66
 065      90             0.76

I want to add new row after the last row with all values '0' in it. So the new df should look like:

Col1     Col2  .....    Col48
 078      abc            0.99
 097      def            0.91
 027      xyz            0.66
 065      bcd             0.76
 0         0             0

After this, I want to replace the Col2 value from 0 to 'Target so the final dataframe would look like:

Col1     Col2  .....    Col48
 078      abc            0.99
 097      def            0.91
 027      xyz            0.66
 065      bcd             0.76
 0        target             0

Code:

 df.loc[len(df)] = 0
 df['Col2'] = df['Col2'].astype(str)
 df['Col2'].str.replace('0','target')
1 Answers

Use setting with enlargement, necesary default RangeIndex:

df.loc[len(df)] = 0
print (df)
   Col1 Col2  Col48
0    78  abc   0.99
1    97  def   0.91
2    27  xyz   0.66
3    65   90   0.76
4     0    0   0.00

Another solution is create one column DataFrame and concat together:

df1 = pd.DataFrame(np.repeat(0, len(df.columns))[None, :], 
                  columns=df.columns,
                  index=[10])

df = pd.concat([df, df1])
print (df)
    Col1 Col2  Col48
0     78  abc   0.99
1     97  def   0.91
2     27  xyz   0.66
3     65   90   0.76
10     0    0   0.00
Related