Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a new row to a Pandas DataFrame with specific index name

I'm trying to add a new row to the DataFrame with a specific index name 'e'.

    number   variable       values
a    NaN       bank          true   
b    3.0       shop          false  
c    0.5       market        true   
d    NaN       government    true   

I have tried the following but it's creating a new column instead of a new row.

new_row = [1.0, 'hotel', 'true']
df = df.append(new_row)

Still don't understand how to insert the row with a specific index. Will be grateful for any suggestions.

like image 295
samba Avatar asked Oct 07 '17 15:10

samba


People also ask

How do I manually add a row to a pandas DataFrame?

The easiest way to add or insert a new row into a Pandas DataFrame is to use the Pandas . append() method. The . append() method is a helper method, for the Pandas concat() function.

How do you add a row in pandas?

You can use the df. loc() function to add a row to the end of a pandas DataFrame: #add row to end of DataFrame df. loc[len(df.

How will you add a column at a specific index to a pandas DataFrame?

Answer. Yes, you can add a new column in a specified position into a dataframe, by specifying an index and using the insert() function. By default, adding a column will always add it as the last column of a dataframe. This will insert the column at index 2, and fill it with the data provided by data .

How do I name a row index in pandas?

You can use the rename() method of pandas. DataFrame to change column/index name individually. Specify the original name and the new name in dict like {original name: new name} to columns / index parameter of rename() . columns is for the column name, and index is for the index name.


3 Answers

You can use df.loc[_not_yet_existing_index_label_] = new_row.

Demo:

In [3]: df.loc['e'] = [1.0, 'hotel', 'true']

In [4]: df
Out[4]:
   number    variable values
a     NaN        bank   True
b     3.0        shop  False
c     0.5      market   True
d     NaN  government   True
e     1.0       hotel   true

PS using this method you can't add a row with already existing (duplicate) index value (label) - a row with this index label will be updated in this case.


UPDATE:

This might not work in recent Pandas/Python3 if the index is a DateTimeIndex and the new row's index doesn't exist.

it'll work if we specify correct index value(s).

Demo (using pandas: 0.23.4):

In [17]: ix = pd.date_range('2018-11-10 00:00:00', periods=4, freq='30min')

In [18]: df = pd.DataFrame(np.random.randint(100, size=(4,3)), columns=list('abc'), index=ix)

In [19]: df
Out[19]:
                      a   b   c
2018-11-10 00:00:00  77  64  90
2018-11-10 00:30:00   9  39  26
2018-11-10 01:00:00  63  93  72
2018-11-10 01:30:00  59  75  37

In [20]: df.loc[pd.to_datetime('2018-11-10 02:00:00')] = [100,100,100]

In [21]: df
Out[21]:
                       a    b    c
2018-11-10 00:00:00   77   64   90
2018-11-10 00:30:00    9   39   26
2018-11-10 01:00:00   63   93   72
2018-11-10 01:30:00   59   75   37
2018-11-10 02:00:00  100  100  100

In [22]: df.index
Out[22]: DatetimeIndex(['2018-11-10 00:00:00', '2018-11-10 00:30:00', '2018-11-10 01:00:00', '2018-11-10 01:30:00', '2018-11-10 02:00:00'], dtype='da
tetime64[ns]', freq=None)
like image 200
MaxU - stop WAR against UA Avatar answered Oct 15 '22 20:10

MaxU - stop WAR against UA


Use append by converting list a dataframe in case you want to add multiple rows at once i.e

df = df.append(pd.DataFrame([new_row],index=['e'],columns=df.columns))

Or for single row (Thanks @Zero)

df = df.append(pd.Series(new_row, index=df.columns, name='e'))

Output:

  number    variable values
a     NaN        bank   True
b     3.0        shop  False
c     0.5      market   True
d     NaN  government   True
e     1.0       hotel   true
like image 27
Bharath Avatar answered Oct 15 '22 20:10

Bharath


If it's the first row you need:

df = Dataframe(columns=[number, variable, values])
df.loc['e', [number, variable, values]] = [1.0, 'hotel', 'true']
like image 42
Kim Miller Avatar answered Oct 15 '22 19:10

Kim Miller