1

I have an existing dataframe like this

>>> print(dataframe)
sid
30      11
56       5
73      25
78       2
132      1
        ..
8531    25
8616     2
9049     1
9125     6
9316    11
Name: name, Length: 87, dtype: int64

I want to add a row like {'sid': 2, '': 100} to it but when I try this

df = pandas.DataFrame({'sid': [2], '': [100]})
df = df.set_index('sid')
dataframe = dataframe.append(df)
print(dataframe)

I end up with

sid              
30    11.0    NaN
56     5.0    NaN
73    25.0    NaN
78     2.0    NaN
132    1.0    NaN
...    ...    ...
8616   2.0    NaN
9049   1.0    NaN
9125   6.0    NaN
9316  11.0    NaN
2      NaN  100.0

I'm hoping for something more like

sid
2       100
30      11
56       5
73      25
78       2
132      1
        ..
8531    25
8616     2
9049     1
9125     6
9316    11

Any idea how I can achieve that?

4
  • Why doesn't the other series have a name? It'd be better if it did... Commented Jul 28, 2020 at 11:56
  • Looks like sid is index name of the series, try dataframe.loc[2] = 100 Commented Jul 28, 2020 at 11:58
  • oh wow loc worked. Thanks @anky! Commented Jul 28, 2020 at 12:05
  • What about axis=1? Commented Jul 28, 2020 at 12:42

2 Answers 2

2

The way to do this was

dataframe.loc[2] = 100

Thanks anky!

Sign up to request clarification or add additional context in comments.

Comments

1

Reason for the above problem, because at the time you have appended two DataFrames, you forgot to set 'sid' as the dataframe index. So, basically the two DataFrames has different structure when you append it. Make sure to set the index of both dataframes same before you append them.

data = [ [30,11], [56, 5], [73, 25]]    #test dataframe 
dataframe = pd.DataFrame(data, columns=['sid', ''])
dataframe = dataframe.set_index('sid')
print(dataframe)

You get,

sid    
30   11
56    5
73   25

Create and set the index of df,

df = pd.DataFrame({'sid' : [2], '' : [100]})
df = df.set_index('sid')

You get,

sid     
2    100

Then append them,

dataframe = df.append(dataframe)
print(dataframe)

You will get the disired outcome,

sid     
2    100
30    11
56     5
73    25

Comments

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.