Home > front end >  How to append 1 row to DataFrame
How to append 1 row to DataFrame

Time:11-09

I have a text file which I read into a pandas DataFrame.

File A:

2009,7,1,3,101,13.03,89.33,0.6,287.69,0
2009,7,1,6,102,19.3,55,1,288.67,0
2009,7,1,9,103,22.33,39.67,1,289.6,0
2009,7,1,12,104,21.97,41,1,295.68,0

Read this into a DataFrame

>>> import pandas as pd
>>> from datetime import datetime as dtdt
>>> par3 = lambda x: dtdt.strptime(x, '%Y %m %d %H')
>>> df3=pd.read_csv('fileA.txt',header=None,parse_dates={'Date': [0,1,2,3]}, date_parser=par3, index_col='Date')
>>> df3
                       4      5      6    7       8  9
Date                                                  
2009-07-01 03:00:00  101  13.03  89.33  0.6  287.69  0
2009-07-01 06:00:00  102  19.30  55.00  1.0  288.67  0
2009-07-01 09:00:00  103  22.33  39.67  1.0  289.60  0
2009-07-01 12:00:00  104  21.97  41.00  1.0  295.68  0

Then, I have new data to be appended into df3 as a new row

bb = '2009-07-01 15:00:00'
cc = '105 18.11 44.55 1.2 300.12 0'

Question how do I append this new row to get

>>> new_df3
                       4      5      6    7       8  9
Date                                                  
2009-07-01 03:00:00  101  13.03  89.33  0.6  287.69  0
2009-07-01 06:00:00  102  19.30  55.00  1.0  288.67  0
2009-07-01 09:00:00  103  22.33  39.67  1.0  289.60  0
2009-07-01 12:00:00  104  21.97  41.00  1.0  295.68  0
2009-07-01 15:00:00  105  18.11  44.55  1.2  300.12  0

This How to append dictionary to DataFrame as a row? did not work in my case, I get either messy results or error messages.

I am aware of the docs https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html, (join): https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html#pandas.DataFrame.join (merge): https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html#pandas.DataFrame.merge but my head already has pretty much exploded. Solution would be very much appreciated.

CodePudding user response:

pandas indexer can make row or column

df.loc[bb] = c.split()
  • Related