VARUN ISAC
VARUN ISAC

Reputation: 443

Adding new data and new column on a pandas dataframe with zero filled

Can any one tell me a way to add a new column and data to an existing dataframe , similar to that shown below. When i enter a new column Name and value , it should add a column with new value at the last and zeroes in all other places, as shown below in pandas dataframe

DataFrame :

A  B  C 
1  2  3
4  5  6

Enter New Column Name: D

Enter New Value: 7

New DataFrame

A  B  C  D
1  2  3  0
4  5  6  0
0  0  0  7

Upvotes: 0

Views: 717

Answers (3)

SeaBean
SeaBean

Reputation: 23227

We can also use .loc with .fillna():

df.loc[df.shape[0], 'D'] = 7
df = df.fillna(0, downcast='infer')

Result:

print(df)

   A  B  C  D
0  1  2  3  0
1  4  5  6  0
2  0  0  0  7

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195593

Other solution, with .append:

print(df.append({"D": 7}, ignore_index=True).fillna(0).astype(int))

Prints:

   A  B  C  D
0  1  2  3  0
1  4  5  6  0
2  0  0  0  7

Upvotes: 1

BENY
BENY

Reputation: 323376

You can create the append df with concat

out = pd.concat([df,pd.DataFrame({'D':[7]})]).fillna(0)
out
     A    B    C    D
0  1.0  2.0  3.0  0.0
1  4.0  5.0  6.0  0.0
0  0.0  0.0  0.0  7.0

Upvotes: 2

Related Questions