To add a new row in a DataFrame for class 12, you can use the loc method if you know the index, or the append method if you want to add it without specifying an index. Here is an example using both methods:
Using loc:
import pandas as pd
# Existing DataFrame
data = {
    'Name': ['Alice', 'Bob'],
    'Class': [10, 11]
}
df = pd.DataFrame(data)
# Add a new row for Class 12 using loc
df.loc[len(df)] = ['Charlie', 12]
print(df)
This methods will give you the following DataFrame:
      Name  Class
0    Alice     10
1      Bob     11
2  Charlie     12
import pandas as pd
# Existing DataFrame
data = {
'Name': ['Alice', 'Bob'],
'Class': [10, 11]
}
df = pd.DataFrame(data)
print(df,"\n \n")
# Add a new row for Class 12 using loc
df.loc[len(df)] = ['Charlie', 12]
df.loc[3] = ['Charlie', 12]
print(df)
Output
Explanation:
- Using 
loc:df.loc[len(df)] = ['Charlie', 12]adds a new row at the end of the DataFrame. 
Add new Column in Existing DataFrame
To add a new column to a DataFrame, you can simply assign a new list or a single value to the DataFrame with the new column name. Here’s how you can do it:
Example
import pandas as pd
# Existing DataFrame
data = {
    'Name': ['Alice', 'Bob'],
    'Class': [10, 11]
}
df = pd.DataFrame(data)
# Add a new column for Class 12
df['Class 12'] = [None, None]  # Initialize with None or some default values
print(df)
For the first example:
    Name  Class Class 12
0  Alice     10    None
1    Bob     11    None
If you have specific values for each row in the new column, you can assign those values directly:
import pandas as pd
# Existing DataFrame
data = {
    'Name': ['Alice', 'Bob'],
    'Class': [10, 11]
}
df = pd.DataFrame(data)
# Add a new column for Class 12 with specific values
df['Class 12'] = ['A+', 'B']
print(df)
Result
For the second example:
    Name  Class Class 12
0  Alice     10      A+
1    Bob     11       B
Explanation:
- Adding a new column with default values: 
df['Class 12'] = [None, None]initializes the new column withNonefor each row. - Adding a new column with specific values: 
df['Class 12'] = ['A+', 'B']initializes the new column with specific values for each row. 

.png)

0 Comments
Please do note create link post in comment section