1

So far, when I needed to add rows to a dataframe, I used loc (or more rarely, iloc). In a dataframe like this one:

                         key1           key2        value
  2014-02-03 12:00:00     22             32         98.89
  2014-02-03 12:00:00     23             33         99.25
  2014-02-03 12:00:00     24             34         99.78
  2014-02-03 15:00:00     22             32         96.54
  2014-02-03 15:00:00     23             33         97.21
  2014-02-03 15:00:00     24             34         98.59

I used:

df.loc[pd.to_datetime('2014-02-03 18:00:00')] = [23, 32, 98.84]

But if I need to add rows with the same index (imagine another row with 2014-02-03 15:00:00) then loc gives me error. I have been trying methods like concat or merge but I don't get anything. Thanks.

1 Answer 1

1

For me works concat with another DataFrame:

df.loc[pd.to_datetime('2014-02-03 18:00:00')] = [23, 32, 98.84]
df1 = pd.DataFrame([[23, 32, 100]], 
                    columns=df.columns, 
                    index=[pd.to_datetime('2014-02-03 15:00:00')])
print (df1)
                     key1  key2  value
2014-02-03 15:00:00    23    32    100

df = pd.concat([df, df1])
print (df)
                    key1  key2   value
2014-02-03 12:00:00   22  32.0   98.89
2014-02-03 12:00:00   23  33.0   99.25
2014-02-03 12:00:00   24  34.0   99.78
2014-02-03 15:00:00   22  32.0   96.54
2014-02-03 15:00:00   23  33.0   97.21
2014-02-03 15:00:00   24  34.0   98.59
2014-02-03 18:00:00   23  32.0   98.84
2014-02-03 15:00:00   23  32.0  100.00
Sign up to request clarification or add additional context in comments.

2 Comments

Hello again :-). Yes, concat works. I was getting in bad order the columns when creating a new dataframe, so that was my problem. But with your df.columns it works. Thanks.
Glad can help. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.