0% found this document useful (0 votes)
6 views

Week 13 2-Calculating Square and Cube of list of numbers in CSV file

The document describes a Python script that reads a CSV file named 'NumData.csv' containing a list of numbers, calculates their squares and cubes, and then saves the results to a new CSV file named 'NumFinal.csv'. It demonstrates the use of the pandas library for data manipulation, including reading, calculating, and writing CSV files. The final output includes the original numbers along with their corresponding square and cube values.

Uploaded by

shost661
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Week 13 2-Calculating Square and Cube of list of numbers in CSV file

The document describes a Python script that reads a CSV file named 'NumData.csv' containing a list of numbers, calculates their squares and cubes, and then saves the results to a new CSV file named 'NumFinal.csv'. It demonstrates the use of the pandas library for data manipulation, including reading, calculating, and writing CSV files. The final output includes the original numbers along with their corresponding square and cube values.

Uploaded by

shost661
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Calculating Square and Cube of list of numbers

in CSV file named 'NumData.csv'


#Reading a File
import pandas as pd
df=pd.read_csv('NumData.csv')
print(df)

Number
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10

#Inserting and calculating Square Column


import pandas as pd
df=pd.read_csv('NumData.csv')
df['Square']=df['Number']**2
print(df)

Number Square
0 1 1
1 2 4
2 3 9
3 4 16
4 5 25
5 6 36
6 7 49
7 8 64
8 9 81
9 10 100

#Inserting and calculating Square and Cube Columns


import pandas as pd
df=pd.read_csv('NumData.csv')
df['Square']=df['Number']**2
df['Cube']=df['Number']**3
print(df)

Number Square Cube


0 1 1 1
1 2 4 8
2 3 9 27
3 4 16 64
4 5 25 125
5 6 36 216
6 7 49 343
7 8 64 512
8 9 81 729
9 10 100 1000

#Saving the DataFrame to a new File


import pandas as pd
df=pd.read_csv('NumData.csv')
df['Square']=df['Number']**2
df['Cube']=df['Number']**3
df.to_csv('NumFinal.csv')
print(df)

Number Square Cube


0 1 1 1
1 2 4 8
2 3 9 27
3 4 16 64
4 5 25 125
5 6 36 216
6 7 49 343
7 8 64 512
8 9 81 729
9 10 100 1000

#Saving the DataFrame to a new File without index


import pandas as pd
df=pd.read_csv('NumData.csv')
df['Square']=df['Number']**2
df['Cube']=df['Number']**3
df.to_csv('NumFinal.csv', index=False)
print(df)

Number Square Cube


0 1 1 1
1 2 4 8
2 3 9 27
3 4 16 64
4 5 25 125
5 6 36 216
6 7 49 343
7 8 64 512
8 9 81 729
9 10 100 1000

You might also like