laszlopanaflex
laszlopanaflex

Reputation: 1916

how to overwrite values of first row of dataframe

Given a panda.Dataframe such as:

df = pd.DataFrame(np.random.randn(10,5), columns = ['a','b','c','d','e'])

I would like to know the best way to replace all values in the first row with a 0 (or some other specific value) and work with the new dataframe. I would like to do this in a general way, where there may be more or less columns than in this example.

Despite the simplicity of the question, I was not able to come across a solution. Most examples posted by others had to do with fillna() and related methods

Upvotes: 1

Views: 8895

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49794

You can use iloc to do that pretty cleanly like:

Code:

df.iloc[0] = 0

Test Code:

df = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
print(df)
df.iloc[0] = 0
print(df)

Results:

          a         b         c         d         e
0  0.715524 -0.914676  0.241008 -1.353033  0.170578
1 -0.300348  1.118491 -0.520407  0.185877 -0.950839
2  1.942239  0.980477  0.110457 -0.558483  0.903775
3  0.400923  1.347769 -0.120445  0.036253  0.683571
4 -0.761881 -0.642469  2.030019  2.274070 -0.067672
5  0.566003  0.263949 -0.567247  0.689599  0.870442
6  1.904812 -0.689312  1.400950  1.942681 -1.268679
7 -0.253381  0.464208  1.362960  0.129433  0.527576
8 -1.404035  0.174586  1.006268  0.007333  1.172559
9  0.330404  0.735610  1.277451 -0.104888  0.528356

          a         b         c         d         e
0  0.000000  0.000000  0.000000  0.000000  0.000000
1 -0.300348  1.118491 -0.520407  0.185877 -0.950839
2  1.942239  0.980477  0.110457 -0.558483  0.903775
3  0.400923  1.347769 -0.120445  0.036253  0.683571
4 -0.761881 -0.642469  2.030019  2.274070 -0.067672
5  0.566003  0.263949 -0.567247  0.689599  0.870442
6  1.904812 -0.689312  1.400950  1.942681 -1.268679
7 -0.253381  0.464208  1.362960  0.129433  0.527576
8 -1.404035  0.174586  1.006268  0.007333  1.172559
9  0.330404  0.735610  1.277451 -0.104888  0.528356

Upvotes: 5

Related Questions