Add column to csv python – Python: Add a Column to an Existing CSV File

Python Add a Column to an Existing CSV File

Methods to add a column to an existing CSV File

Add column to csv python: In this article, we will discuss how to add a column to an existing CSV file using csv.reader and csv.DictWriter  classes. Apart from appending the columns, we will also discuss how to insert columns in between other columns of the existing CSV file.

We also include these for beginners:

  • Add a list as a column to an existing csv file python
  • Add column from one csv to another python
  • Add column to existing csv
  • Add two columns in csv python
  • Add column to csv powershell
  • Python csv write to specific row and column
  • Add column to existing csv
  • Add two columns in csv python
  • Add column to csv powershell
  • Add a list as a column to an existing csv file python
  • Add column from one csv to another python
  • Python add a column to an existing csv file
  • Python add a new column to csv
  • Python add csv column to list
  • Python pandas append column to csv
  • Add a line to a csv file python

Original CSV file content

total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4
  • Method 1-Add a column with the same values to an existing CSV file

Python add column to csv: In this, we see how we make one column and add it to our CSV file but all the values in this column are the same.

Steps will be to append a column in CSV file are,

  1. Open ‘input.csv’ file in read mode and create csv.reader object for this CSV file
  2. Open ‘output.csv’ file in write mode and create csv.writer object for this CSV file
  3. Using reader object, read the ‘input.csv’ file line by line
  4. For each row (read like a list ), append default text in the list.
  5. Write this updated list / row in the ‘output.csv’ using csv.writer object for this file.
  6. Close both input.csv and output.csv file.

Let see this with the help of an example

from csv import writer
from csv import reader
default_text = 'New column'
# Open the input_file in read mode and output_file in write mode
with open('example1.csv', 'r') as read_obj, \
        open('output_1.csv', 'w', newline='') as write_obj:
    # Create a csv.reader object from the input file object
    csv_reader = reader(read_obj)
    # Create a csv.writer object from the output file object
    csv_writer = writer(write_obj)
    # Read each row of the input csv file as list
    for row in csv_reader:
        # Append the default text in the row / list
        row.append(default_text)
        # Add the updated row / list to the output file
        csv_writer.writerow(row)
output_data=pd.read_csv('output_1.csv')
output_data.head()

Output

total_bill tip sex smoker day time size New column
0 16.99 1.01 Female No Sun Dinner 2 New column
1 10.34 1.66 Male No Sun Dinner 3 New column
2 21.01 3.50 Male No Sun Dinner 3 New column
3 23.68 3.31 Male No Sun Dinner 2 New column
4 24.59 3.61 Female No Sun Dinner 4 New column

Here we see that new column is added but all value in this column is same.

Now we see how we can add different values in the column.

  •  Method 2-Add a column to an existing CSV file, based on values from other columns

How to add a new column to a csv file using python: In this method how we can make a new column but in this column the value we add will be a combination of two or more columns. As we know there is no direct function to achieve so we have to write our own function to achieve this task. Let see the code for this.

from csv import writer
from csv import reader
def add_column_in_csv(input_file, output_file, transform_row):
    """ Append a column in existing csv using csv.reader / csv.writer classes"""
    # Open the input_file in read mode and output_file in write mode
    with open(input_file, 'r') as read_obj, \
            open(output_file, 'w', newline='') as write_obj:
        # Create a csv.reader object from the input file object
        csv_reader = reader(read_obj)
        # Create a csv.writer object from the output file object
        csv_writer = writer(write_obj)
        # Read each row of the input csv file as list
        for row in csv_reader:
            # Pass the list / row in the transform function to add column text for this row
            transform_row(row, csv_reader.line_num)
            # Write the updated row / list to the output file
            csv_writer.writerow(row)
add_column_in_csv('example1.csv', 'output_2.csv', lambda row, line_num: row.append(row[0] + '__' + row[1]))
output_data=pd.read_csv('output_2.csv')
output_data.head()

Output

total_bill tip sex smoker day time size total_bill__tip
0 16.99 1.01 Female No Sun Dinner 2 16.99__1.01
1 10.34 1.66 Male No Sun Dinner 3 10.34__1.66
2 21.01 3.50 Male No Sun Dinner 3 21.01__3.5
3 23.68 3.31 Male No Sun Dinner 2 23.68__3.31
4 24.59 3.61 Female No Sun Dinner 4 24.59__3.61

Here we see the new column is formed as the combination of the values of the 1st and 2nd column.

Explanation:

In the Lambda function, we received each row as a list and the line number. It then added a value in the list and the value is a merger of the first and second value of the list. It appended the column in the contents of example1.csv by merging values of the first and second columns and then saved the changes as output_2.csv files.

  • Method 3-Add a list as a column to an existing csv file

Python csv write column: In this method, we will add our own value in the column by making a list of our values and pass this into the function that we will make. Let see the code for this.

from csv import writer
from csv import reader
def add_column_in_csv(input_file, output_file, transform_row):
    """ Append a column in existing csv using csv.reader / csv.writer classes"""
    # Open the input_file in read mode and output_file in write mode
    with open(input_file, 'r') as read_obj, \
            open(output_file, 'w', newline='') as write_obj:
        # Create a csv.reader object from the input file object
        csv_reader = reader(read_obj)
        # Create a csv.writer object from the output file object
        csv_writer = writer(write_obj)
        # Read each row of the input csv file as list
        for row in csv_reader:
            # Pass the list / row in the transform function to add column text for this row
            transform_row(row, csv_reader.line_num)
            # Write the updated row / list to the output file
            csv_writer.writerow(row)
l=[]
l.append("New Column")
rows = len(data.axes[0])
for i in range(rows):
    val=i+1
    l.append(val)
add_column_in_csv('example1.csv', 'output_3.csv', lambda row, line_num: row.append(l[line_num - 1]))
output_data=pd.read_csv('output_3.csv')
output_data.head()

Output

total_bill tip sex smoker day time size New Column
0 16.99 1.01 Female No Sun Dinner 2 1
1 10.34 1.66 Male No Sun Dinner 3 2
2 21.01 3.50 Male No Sun Dinner 3 3
3 23.68 3.31 Male No Sun Dinner 2 4
4 24.59 3.61 Female No Sun Dinner 4 5

Explanation

In the Lambda function, we received each row as a list and the line number. It then added a value in the list and the value is an entry from our list l at index  line_num – 1.Thus all the entries in the list l are added as a column in the CSV.

So these are some of the methods to add new column in csv.

Test yourself:

  1. Write to a specific column in csv python pandas?
  2. Write to specific column csv python?
  3. How do i add a column to an existing csv file in python?
  4. How to add column in existing csv file using python?

 

Python pythagorean triples – Program to Determine all Pythagorean Triplets in the Range in C++ and Python

Program to Determine all Pythagorean Triplets in the Range in C++ and Python

Python pythagorean triples: In the previous article, we have discussed about Program to Print Collatz Conjecture for a Given Number in C++ and Python. Let us learn Program to Determine all Pythagorean Triplets in C++ Program.

A Pythagorean triplet is a collection of three positive numbers, a, b, and c, such that a^2 + b^2 = c^2. Some things you have to notice while reading.

  • Program to check pythagorean triples in c
  • Pythagorean triples list
  • Pythagorean triples program in java
  • Pythagorean triples in python assignment expert
  • Pythagorean triples leetcode
  • Pythagorean triples hackerrank solution

Given a limit, find all Pythagorean Triples with values less than that limit.

Examples:

Example1:

Input:

given upper limit =63

Output:

printing the Pythagorean triplets till the upper limit 63 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61

Example2:

Input:

given upper limit =175

Output:

printing the Pythagorean triplets till the upper limit 175 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61
48 14 50
45 28 53
40 42 58
33 56 65
24 70 74
13 84 85
63 16 65
60 32 68
55 48 73
48 64 80
39 80 89
28 96 100
15 112 113
80 18 82
77 36 85
72 54 90
65 72 97
56 90 106
45 108 117
32 126 130
17 144 145
99 20 101
96 40 104
91 60 109
84 80 116
75 100 125
64 120 136
51 140 149
36 160 164

Find all Pythagorean triplets in the given range in C++ and Python

Pythagorean triples c program: A simple solution is to use three nested loops to generate these triplets that are less than the provided limit. Check if the Pythagorean condition is true for each triplet; if so, print the triplet. This solution has a time complexity of O(limit3), where ‘limit’ is the stated limit.

An Efficient Solution will print all triplets in O(k) time, where k is the number of triplets to be printed. The solution is to apply the Pythagorean triplet’s square sum connection, i.e., addition of squares a and b equals square of c, and then represent these numbers in terms of m and n.

For every choice of positive integer m and n, the formula of Euclid creates Pythagorean Triplets:

a=m^2 -n^2

b= 2 * m * n

c= m ^2 +n^2

Below is the implementation of efficient solution in C++ and Python:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)Finding all Pythagorean till the given limit in Python

Approach:

  • Scan the upper limit or give static input and save the variable.
  • Calculate the Pythagorean triplets using the formula with a while loop and for loop.
  • If the c value exceeds the upper limit, or if a number equals 0, break from the loop.
  • Print down all Pythagorean triplets’ three numbers.
  • Exit of program.

Below is the implementation:

# enter the upper limit till you find pythagorean triplets
upper_limit = 63
n3 = 0
a = 2
print("printing the pythagorean triplets till the upper limit", upper_limit, ":")
while(n3 < upper_limit):
    for b in range(1, a+1):
        n1 = a*a-b*b
        n2 = 2*a*b
        n3 = a*a+b*b
        if(n3 > upper_limit):
            break
        if(n1 == 0 or n2 == 0 or n3 == 0):
            break
        print(n1, n2, n3)
    a = a+1

Output:

printing the Pythagorean triplets till the upper limit 63 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61

Explanation:

The upper limit / input should be entered by a user as static, and stored in a variable.
The value of Pythagorean triplets using the formula is used during and for loops.
The loop breaks out if the value of a side is greater than the upper boundary, or if one side is 0.
The triplets will then be printed.

2)Finding all Pythagorean till the given limit in C++

Approach:

  • Scan the upper limit using cin or give static input and save the variable.
  • Calculate the Pythagorean triplets using the formula with a while loop and for loop.
  • If the c value exceeds the upper limit, or if a number equals 0, break from the loop.
  • Print down all Pythagorean triplets’ three numbers.
  • Exit of program.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{

    // enter the upper limit till you find pythagorean
    // triplets
    int upper_limit = 175;
    int n3 = 0;
    int a = 2;
    cout << "printing the pythagorean triplets till the "
            "upper limit"
         << upper_limit << ":" << endl;
    while (n3 < upper_limit) {
        for (int b = 1; b <= a; b++) {
            int n1 = a * a - b * b;
            int n2 = 2 * a * b;
            n3 = a * a + b * b;
            if (n3 > upper_limit)
                break;
            if (n1 == 0 or n2 == 0 or n3 == 0)
                break;
            cout << n1 << " " << n2 << " " << n3 << endl;
        }
        a = a + 1;
    }
    return 0;
}

Output:

printing the Pythagorean triplets till the upper limit175:
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61
48 14 50
45 28 53
40 42 58
33 56 65
24 70 74
13 84 85
63 16 65
60 32 68
55 48 73
48 64 80
39 80 89
28 96 100
15 112 113
80 18 82
77 36 85
72 54 90
65 72 97
56 90 106
45 108 117
32 126 130
17 144 145
99 20 101
96 40 104
91 60 109
84 80 116
75 100 125
64 120 136
51 140 149
36 160 164

Answer yourself:

  1. Write a program to print all pythagorean triplets between 1 to 100?
  2. Find all pythagorean triples below the given limit?
  3. Program to determine all pythagorean triplets in the range in c++ and python?

Related Programs:

Python Program to Take in the Marks of 5 Subjects and Display the Grade

Program to Take in the Marks of 5 Subjects and Display the Grade

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Given the marks of 5 subjects of the student, the task is to display the grade of the student based on the marks in Python.

Read Also: Python Program for Swapping Three Variables Without Using any Temporary Variable.

Examples:

Example1:

Input:

Enter first subject marks as integer = 75
Enter second subject marks as integer = 79
Enter third subject marks as integer = 65
Enter fourth subject marks as integer = 82
Enter fifth subject marks as integer = 63

Output:

Average of 5 marks = 72.8 Grade =C

Example2:

Input:

Enter first subject marks as integer = 63
Enter second subject marks as integer = 19
Enter third subject marks as integer = 99
Enter fourth subject marks as integer = 85
Enter fifth subject marks as integer = 73

Output:

Average of 5 marks = 67.8 Grade =D

Program to Take in the Marks of 5 Subjects and Display the Grade in Python

There are several ways to calculate the grade of the student based on the marks of 5 subjects in Python some of them are:

Method #1:Using IF..elif..else Statements(Static Input)

Approach:

  • Give the 5 subject marks as static input and store them in 5 variables.
  • Calculate the sum of the 5 subject marks and store it in a variable.
  • Divide the sum by 5 to get the average of all the given marks.
  • To determine the grade based on the average of the marks, use an if…Elif..else conditions.
  • Print the grade.
  • The Exit of the Program.

Below is the implementation:

# Give the 5 subject marks as static input and store them in 5 variables.
marks1 = 95
marks2 = 85
marks3 = 89
marks4 = 93
marks5 = 87
# Calculate the sum of the 5 subject marks and store it in a variable.
summarks = marks1+marks2+marks3+marks4+marks5
# Divide the sum of marks by 5 to get the average of all the given marks.
avgmark = summarks/5
# To determine the grade based on the average of the marks, use an if...Elif..else conditions.
if(avgmark >= 90):
    print("Average of 5 marks =", avgmark, 'Grade =A')
elif(avgmark >= 80 and avgmark < 90):
    print("Average of 5 marks =", avgmark, 'Grade =B')
elif(avgmark >= 70 and avgmark < 80):
    print("Average of 5 marks =", avgmark, 'Grade =C')
elif(avgmark >= 60 and avgmark < 70):
    print("Average of 5 marks =", avgmark, 'Grade =D')
else:
    print("Average of 5 marks =", avgmark, 'Grade =E')

Output:

Average of 5 marks = 89.8 Grade =B

Explanation:

  • The user must enter 5 different values as static input and store them in different variables.
  • Then add together all five marks and divide by five to get the average.
  • If the average is more than 90, the grade is displayed as “A.”
  • If the average is between 80 and 90, the letter “B” is printed.
  • If the average is between 70 and 80, the letter “C” is printed.
  • If the average is between 60 and 70, the letter “D” is printed.
  • If the average falls below 60, the letter “F” is printed.

Method #2:Using IF..elif..else Statements (User Input separated by newline)

Approach:

  • Give the 5 subject marks as user input using int(input()) which converts the string to an integer.
  • Store them in 5 separate variables.
  • Calculate the sum of the 5 subject marks and store it in a variable.
  • Divide the sum by 5 to get the average of all the given marks.
  • To determine the grade based on the average of the marks, use an if…Elif..else conditions.
  • Print the grade.
  • The Exit of the Program.

Below is the implementation:

# Give the 5 subject marks as user input using int(input()) which converts the string to an integer.
# Store them in 5 separate variables.
marks1 = int(input('Enter first subject marks as integer = '))
marks2 = int(input('Enter second subject marks as integer = '))
marks3 = int(input('Enter third subject marks as integer = '))
marks4 = int(input('Enter fourth subject marks as integer = '))
marks5 = int(input('Enter fifth subject marks as integer = '))
# Calculate the sum of the 5 subject marks and store it in a variable.
summarks = marks1+marks2+marks3+marks4+marks5
# Divide the sum of marks by 5 to get the average of all the given marks.
avgmark = summarks/5
# To determine the grade based on the average of the marks, use an if...Elif..else conditions.
if(avgmark >= 90):
    print("Average of 5 marks =", avgmark, 'Grade =A')
elif(avgmark >= 80 and avgmark < 90):
    print("Average of 5 marks =", avgmark, 'Grade =B')
elif(avgmark >= 70 and avgmark < 80):
    print("Average of 5 marks =", avgmark, 'Grade =C')
elif(avgmark >= 60 and avgmark < 70):
    print("Average of 5 marks =", avgmark, 'Grade =D')
else:
    print("Average of 5 marks =", avgmark, 'Grade =E')

Output:

Enter first subject marks as integer = 75
Enter second subject marks as integer = 79
Enter third subject marks as integer = 65
Enter fourth subject marks as integer = 82
Enter fifth subject marks as integer = 63
Average of 5 marks = 72.8 Grade =C

Method #3:Using IF..elif..else Statements and map(),split() functions (User Input separated by spaces)

Approach:

  • Give the 5 subject marks as user input separated by spaces using map(), split() functions.
  • Store them in 5 separate variables.
  • Calculate the sum of the 5 subject marks and store it in a variable.
  • Divide the sum by 5 to get the average of all the given marks.
  • To determine the grade based on the average of the marks, use an if…Elif..else conditions.
  • Print the grade.
  • The Exit of the Program.

Below is the implementation:

# Give the 5 subject marks as user input separated by spaces using map(), split() functions.
# Store them in 5 separate variables.
marks1, marks2, marks3, marks4, marks5 = map(int, input(
    'Enter 5 subject marks separated by spaces = ').split())
# Calculate the sum of the 5 subject marks and store it in a variable.
summarks = marks1+marks2+marks3+marks4+marks5
# Divide the sum of marks by 5 to get the average of all the given marks.
avgmark = summarks/5
# To determine the grade based on the average of the marks, use an if...Elif..else conditions.
if(avgmark >= 90):
    print("Average of 5 marks =", avgmark, 'Grade =A')
elif(avgmark >= 80 and avgmark < 90):
    print("Average of 5 marks =", avgmark, 'Grade =B')
elif(avgmark >= 70 and avgmark < 80):
    print("Average of 5 marks =", avgmark, 'Grade =C')
elif(avgmark >= 60 and avgmark < 70):
    print("Average of 5 marks =", avgmark, 'Grade =D')
else:
    print("Average of 5 marks =", avgmark, 'Grade =E')

Output:

Enter 5 subject marks separated by spaces = 45 96 78 99 92
Average of 5 marks = 82.0 Grade =B

Read Also:

  1. Python program to create grade calculator?
  2. Python program to find grade of a student using if else?
  3. Student mark list program in python using for loop?
  4. Python program to find average and grade for given marks?
  5. Write a program to take in the marks of 5 subjects and display the grade in c?
  6. Python program to calculate total marks percentage and grade of a student?
  7. Student mark list program in python using function?
  8. Student mark list program in python using class?
  9. Write a program to enter marks of 5 subjects and calculate percentage and division?
  10. Write a program to display student name and marks in python?
  11. Python program to create grade calculator?
  12. Python program to take in the marks of 5 subjects and display the grade?
  13. Write a python program to take in the marks of 5 subjects and display the grade?

Related Programs:

Python Program to Print nth Iteration of Lucas Sequence

Program to Print nth Iteration of Lucas Sequence

In the previous article, we have discussed Python Program to Find Sum of Geometric Progression Series

Definition of Lucas sequence:

We’ve all heard of the Fibonacci sequence. It is a sequence in which each term is the sum of the two preceding terms. The Lucas sequence is the same as the previous one, but with different starting values. A Fibonacci sequence starts with 0 and 1, whereas a Lucas sequence in python starts with 2 and 1. The other terms in the Lucas sequence are 3, 4, 7, 11, Nth Lucas Number In Python, Lucas Series In Python, Lucas Series In Java and so on.

Given a number ‘n’ and the task is to print the given nth iteration of Lucas Sequence.

Examples:

Example1:

Input:

n = 6

Output:

The above Given nth iteration of Lucas Sequence =  18

Example 2:

Input:

n = 10

Output:

The above Given nth iteration of Lucas Sequence =  123

Program to Print nth Iteration of Lucas Sequence

Below are the ways to get the given nth Iteration of the Lucas Sequence.

Method #1: Using For Loop  (Static Input)

Approach:

  • Give the First term =2 (since the first term in Lucas Sequence is 2 which is a constant) as static input and store it in a variable.
  • Give the Second term =1 (since the second term in Lucas Sequence is 1 which is a constant) as static input and store it in another variable.
  • Give the number as static input and store it in another variable.
  • Loop from ‘1’ to the above given n+1 value (since doesn’t include the last term) range using For loop.
  • Inside the loop, get the third term which is the sum of the first and the second term, and store it in a variable.
  • Assign the value of the second term to the first term.
  • Assign the value of the third term to the second term and come out of For Loop.
  • Print the Value of the above given nth iteration of Lucas Sequence(i.e. first term).
  • The Exit of the program.

Below is the implementation:

# Give the First term =2 (since the first term in Lucas Sequence is 2 which is a constant)
# as static input and store it in a variable.
fst_trm = 2
# Give the Second term =1 (since the second term in Lucas Sequence is 1 which is a constant)
# as static input and store it in another variable.
secnd_trm = 1
# Give the number as static input and store it in another variable.
gvn_n_vlue = 6
# Loop from '1' to the above given n+1 value (since doesn't include last term) range
# using For loop.
for i in range(1, gvn_n_vlue+1):
 # Inside the loop , get the third term which is the sum of first and the second term
    # and store it in a variable.
    third_trm = fst_trm+secnd_trm
 # Assign the value of second term to the first term.
    fst_trm = secnd_trm
  # Assign the value of the third term to the second term and come out of For Loop.
    secnd_trm = third_trm
# Print the Value of above given nth iteration of Lucas Sequence(i.e. first term).
print("The above Given nth iteration of Lucas Sequence = ", fst_trm)

Output:

The above Given nth iteration of Lucas Sequence =  18

Method #2: Using For Loop  (User Input)

Approach:

  • Give the First term =2 (since the first term in Lucas Sequence is 2 which is a constant) as static input and store it in a variable.
  • Give the Second term =1 (since the second term in Lucas Sequence is 1 which is a constant) as static input and store it in another variable.
  • Give the number as User input and store it in another variable.
  • Loop from ‘1’ to the above given n+1 value (since doesn’t include the last term) range using For loop.
  • Inside the loop, get the third term which is the sum of the first and the second term, and store it in a variable.
  • Assign the value of the second term to the first term.
  • Assign the value of the third term to the second term and come out of For Loop.
  • Print the Value of the above given nth iteration of Lucas Sequence(i.e. first term).
  • The Exit of the program.

Below is the implementation:

# Give the First term =2 (since the first term in Lucas Sequence is 2 which is a constant)
# as static input and store it in a variable.
fst_trm = 2
# Give the Second term =1 (since the second term in Lucas Sequence is 1 which is a constant)
# as static input and store it in another variable.
secnd_trm = 1
# Give the number as User input and store it in another variable.
gvn_n_vlue = int(input("Enter Some Random number = "))
# Loop from '1' to the above given n+1 value (since doesn't include last term) range
# using For loop.
for i in range(1, gvn_n_vlue+1):
 # Inside the loop , get the third term which is the sum of first and the second term
    # and store it in a variable.
    third_trm = fst_trm+secnd_trm
 # Assign the value of second term to the first term.
    fst_trm = secnd_trm
  # Assign the value of the third term to the second term and come out of For Loop.
    secnd_trm = third_trm
# Print the Value of above given nth iteration of Lucas Sequence(i.e. first term).
print("The above Given nth iteration of Lucas Sequence = ", fst_trm)

Output:

Enter Some Random number = 10
The above Given nth iteration of Lucas Sequence = 123

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Read more: Python Program to Find Vertex, Focus and Directrix of Parabola

Solve these:

  1. Print The Nth Lucas Number In Python?
  2. Given A Number N, Print The Nth Lucas Numbers python. Numbering Starts From 0?

Related Posts On:

Negative numbers in python – Python Program to Print Sum of Negative Numbers, Positive Even Numbers and Positive Odd numbers in a List

Program to Print Sum of Negative Numbers, Positive Even Numbers and Positive Odd numbers in a List

Negative numbers in python: Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

List in Python :

The list data type is one of the most often used data types in Python. The square brackets [ ] easily identify a Python List. Lists are used to store data items, with each item separated by a comma (,). A Python List can include data elements of any data type, including integers and Booleans.

One of the primary reasons that lists are so popular is that they are mutable. Any data item in a List can be replaced by any other data item if it is mutable. This distinguishes Lists from Tuples, which are likewise used to store data elements but are immutable.

Given a list the task is to print the sum of all positive even numbers ,odd numbers and negative numbers in the given list in python.

Examples:

Example1:

Input:

given list =[23, 128, -4, -19, 233, 726, 198, 199, 203, -13]

Output:

The sum of all positive even numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = 1052
The sum of all positive odd numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = 658
The sum of all positive negative numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = -36

Example2:

Input:

given list =[-4, 23, 12, -13, 234, 198, 55, -19, 87, 45]

Output:

The sum of all positive even numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45]  = 444 
The sum of all positive odd numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45] =  210 
The sum of all positive negative numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45] =  -36

Python Program to Print Sum of Negative Numbers, Positive Even Numbers and Positive Odd numbers in a List

Below are the ways to print the sum of all positive even numbers ,odd numbers and negative numbers in the given list in python.

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1:Using append() and Conditional Statements (User Input separated by newline)

Approach:

  • Take the user’s input on the number of elements to include in the list.
  •  Using a for loop, Scan the elements from the user and append them to a list.
  • Using a for loop, retrieve the elements from the list one at a time, determine whether they are positive odd, positive even or negative numbers and append them to various lists say posEven, posOdd ,negNum.
  • Calculate the sum of posEven, posOdd ,negNum and print them
  • Exit of program

Below is the implementation:

# scanning the total number of elements of the given list
totalCount = int(
    input("Enter the total number of elements of the given list = "))
# Taking a empty list
given_list = []
# Using for loop to loop totalCount times
for i in range(totalCount):
    eleme = int(input("Enter some random element(integer) = "))
    given_list.append(eleme)
# Taking three empty lists which stores positive
# ven numbers ,positive odd numbers and negative numbers
posEven = []
posOdd = []
negNum = []
# Traversing the list using for loop
for element in given_list:
    # checking if the number is greater than 0
    if(element > 0):
        # if the element is even then add this element to posEven using append() function
        if(element % 2 == 0):
            posEven.append(element)
    # if the element is even then add this element to posOdd using append() function
        else:
            posOdd.append(element)
    # else if the number is less than 0 then add to negNum list using append() function
    else:
        negNum.append(element)
        

# Calculating sum
posEvensum = sum(posEven)
posOddsum = sum(posOdd)
negNumsum = sum(negNum)
# printing the respectve sum's
print("The sum of all positive even numbers in thee given list = ",
      given_list, posEvensum)
print("The sum of all positive odd numbers in thee given list = ", given_list, posOddsum)
print("The sum of all positive negative numbers in thee given list = ",
      given_list, negNumsum)

Output:

Enter the total number of elements of the given list = 10
Enter some random element(integer) = -4
Enter some random element(integer) = 23
Enter some random element(integer) = 12
Enter some random element(integer) = -13
Enter some random element(integer) = 234
Enter some random element(integer) = 198
Enter some random element(integer) = 55
Enter some random element(integer) = -19
Enter some random element(integer) = 87
Enter some random element(integer) = 45
The sum of all positive even numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45]  = 444
The sum of all positive odd numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45] =  210
The sum of all positive negative numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45] =  -36

Method #2:Using append() and Conditional Statements (Static Input separated by spaces)

Approach:

  • Given the input of the list as static.
  • Using a for loop, retrieve the elements from the list one at a time, determine whether they are positive odd, positive even or negative numbers and append them to various lists say posEven, posOdd ,negNum.
  • Calculate the sum of posEven, posOdd ,negNum and print them
  • Exit of program

Below is the implementation:

# given list
given_list = [23, 128, -4, -19, 233, 726, 198, 199, 203, -13]
# Taking three empty lists which stores positive
# even numbers ,positive odd numbers and negative numbers
posEven = []
posOdd = []
negNum = []
# Traversing the list using for loop
for element in given_list:
    # checking if the number is greater than 0
    if(element > 0):
        # if the element is even then add this element to posEven using append() function
        if(element % 2 == 0):
            posEven.append(element)
    # if the element is even then add this element to posOdd using append() function
        else:
            posOdd.append(element)
    # else if the number is less than 0 then add to negNum list using append() function
    else:
        negNum.append(element)


# Calculating sum
posEvensum = sum(posEven)
posOddsum = sum(posOdd)
negNumsum = sum(negNum)
# printing the respectve sum's
print("The sum of all positive even numbers in thee given list ",
      given_list, "=", posEvensum)
print("The sum of all positive odd numbers in thee given list ",
      given_list, "=", posOddsum)
print("The sum of all positive negative numbers in thee given list ",
      given_list, "=", negNumsum)

Output:

The sum of all positive even numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = 1052
The sum of all positive odd numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = 658
The sum of all positive negative numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = -36

Related Programs:

Python number to binary string – Python Program to Flipping the Binary Bits

Program to Flipping the Binary Bits

Python number to binary string: Given a binary string, the task is to flip the bits in the given binary string in Python.

Examples:

Example1:

Input:

Given Binary string =1101010001001

Output:

The given binary string before flipping bits is [ 1101010001001 ]
The given binary string after flipping bits is [ 0010101110110 ]

Example2:

Input:

Given Binary string =00110011111

Output:

The given binary string before flipping bits is [ 00110011111 ]
The given binary string after flipping bits is [ 11001100000 ]

Program to Flipping the Binary Bits in Python

Below are the ways to flip the bits in the given binary string in Python.

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the binary string as static input and store it in a variable.
  • Take an empty string(say flipbinary) which is the result after flipping the bits and initialize its value to a null string using “”.
  • Traverse the given binary string using For loop.
  • If the bit is 1 then concatenate the flipbinary with 0.
  • Else concatenate the flipbinary with 1.
  • Print the modified binary string after flipping the bits.
  • The Exit of the Program.

Below is the implementation:

# Give the binary string as static input and store it in a variable.
gvnbinstring = '1101010001001'
# Take an empty string(say flipbinary) which is the result after flipping the bits
# and initialize its value to a null string using "".
flipbinary = ""
# Traverse the given binary string using For loop.
for bitval in gvnbinstring:
    # If the bit is 1 then concatenate the flipbinary with 0.
    if bitval == '1':
        flipbinary += '0'
    # Else concatenate the flipbinary with 1.
    else:
        flipbinary += '1'
# Print the modified binary string after flipping the bits.
print('The given binary string before flipping bits is [', gvnbinstring, ']')
print('The given binary string after flipping bits is [', flipbinary, ']')

Output:

The given binary string before flipping bits is [ 1101010001001 ]
The given binary string after flipping bits is [ 0010101110110 ]

Method #2: Using For Loop (User Input)

Approach:

  • Give the binary string as user input using input() and store it in a variable.
  • Take an empty string(say flipbinary) which is the result after flipping the bits and initialize its value to a null string using “”.
  • Traverse the given binary string using For loop.
  • If the bit is 1 then concatenate the flipbinary with 0.
  • Else concatenate the flipbinary with 1.
  • Print the modified binary string after flipping the bits.
  • The Exit of the Program.

Below is the implementation:

# Give the binary string as user input using input() and store it in a variable.
gvnbinstring = input('Enter some random binary string = ')
# Take an empty string(say flipbinary) which is the result after flipping the bits
# and initialize its value to a null string using "".
flipbinary = ""
# Traverse the given binary string using For loop.
for bitval in gvnbinstring:
    # If the bit is 1 then concatenate the flipbinary with 0.
    if bitval == '1':
        flipbinary += '0'
    # Else concatenate the flipbinary with 1.
    else:
        flipbinary += '1'
# Print the modified binary string after flipping the bits.
print('The given binary string before flipping bits is [', gvnbinstring, ']')
print('The given binary string after flipping bits is [', flipbinary, ']')

Output:

Enter some random binary string = 0011100110101010
The given binary string before flipping bits is [ 0011100110101010 ]
The given binary string after flipping bits is [ 1100011001010101 ]

Method #3: Using replace() function (Static Input)

Approach:

  • Give the binary string as static input and store it in a variable.
  • Replace all 1’s present in the given binary string with some random character like p.
  • Replace all 0’s present in the given binary string with 1.
  • Replace all p’s present in the given binary string with 0.
  • Here ‘p’ acts as a temporary variable.
  • Print the modified binary string after flipping the bits.
  • The Exit of the Program.

Below is the implementation:

# Give the binary string as static input and store it in a variable.
gvnbinstring = '1101010001001'

# Replace all 1's present in the given binary string
# with some random character like p.
flipbinary = gvnbinstring.replace('1', 'p')
# Replace all 0's present in the given
# binary string with 1.
flipbinary = flipbinary.replace('0', '1')
# Replace all p's present in the given
# binary string with 0.
# Here 'p' acts as a temporary variable.
flipbinary = flipbinary.replace('p', '0')
# Print the modified binary string after flipping the bits.
print('The given binary string before flipping bits is [', gvnbinstring, ']')
print('The given binary string after flipping bits is [', flipbinary, ']')

Output:

The given binary string before flipping bits is [ 1101010001001 ]
The given binary string after flipping bits is [ 0010101110110 ]

Method #4: Using replace() function (User Input)

Approach:

  • Give the binary string as user input using input() and store it in a variable.
  • Replace all 1’s present in the given binary string with some random character like p.
  • Replace all 0’s present in the given binary string with 1.
  • Replace all p’s present in the given binary string with 0.
  • Here ‘p’ acts as a temporary variable.
  • Print the modified binary string after flipping the bits.
  • The Exit of the Program.

Below is the implementation:

# Give the binary string as user input using input() and store it in a variable.
gvnbinstring = input('Enter some random binary string = ')

# Replace all 1's present in the given binary string
# with some random character like p.
flipbinary = gvnbinstring.replace('1', 'p')
# Replace all 0's present in the given
# binary string with 1.
flipbinary = flipbinary.replace('0', '1')
# Replace all p's present in the given
# binary string with 0.
# Here 'p' acts as a temporary variable.
flipbinary = flipbinary.replace('p', '0')
# Print the modified binary string after flipping the bits.
print('The given binary string before flipping bits is [', gvnbinstring, ']')
print('The given binary string after flipping bits is [', flipbinary, ']')

Output:

Enter some random binary string = 00110011111
The given binary string before flipping bits is [ 00110011111 ]
The given binary string after flipping bits is [ 11001100000 ]

Related Programs:

Max element in list python – Python Program to Get the Position of Max Value in a List

Program to Get the Position of Max Value in a List

Max element in list python: In the previous article, we have discussed Python Program to Find Vertex, Focus and Directrix of Parabola
max() function :

max() is a built-in function that returns the maximum value in a list.

index() function:

This function searches the lists. It returns the index where the value is found when we pass it as an argument that matches the value in the list. If no value is found, Value Error is returned.

Given a list, the task is to Get the position of Max Value in a List.

Examples:

Example 1 :

Input :

Given List = [1, 5, 9, 2, 7, 3, 8]

Output:

Maximum Value in the above Given list = 9
Position of Maximum value of the above Given List = 3

Example 2 :

Input : 

Given List = [4, 3, 7, 1, 2, 8, 9]

Output:

Maximum Value in the above Given list = 9
Position of Maximum value of the above Given List = 7

Program to Get the Position of Max Value in a List

Below are the ways to Get the Position of Max value in a List.

Method #1: Using Max(),Index() functions  (Static Input)

Approach:

  • Give the List as static input and store it in a variable.
  • Get the maximum value of the given list using the built-in max() function and store it in another variable.
  • Print the maximum value of the above-given List.
  • Get the position of the maximum value of the given List using the built-in index() function and store it in another variable.
  • Print the position of the maximum value of the given List i.e. maximum position+1( since list index starts from zero).
  • The Exit of the program.

Below is the implementation:

# Give the List as static input and store it in a variable.
Gvn_lst = [1, 5, 9, 2, 7, 3, 8]
# Get the maximum value of the given list using the built-in max() function and
# store it in another variable
maxim_vle = max(Gvn_lst)
# Print the maximum value of the above given List.
print("Maximum Value in the above Given list = ", maxim_vle)
# Get the position of the maximum value of the List using the built-in index() function
# and store it in another variable.
maxim_positn = Gvn_lst.index(maxim_vle)
# Print the position of the maximum value of the given List i.e. maximum position+1
# ( since list index starts from zero).
print("Position of Maximum value of the above Given List = ", maxim_positn+1)

Output:

Maximum Value in the above Given list =  9
Position of Maximum value of the above Given List =  3

Method #2: Using Max(),Index() functions  (User Input)

Approach:

  • Give the list as User input using list(),map(),input(),and split() functions and store it in a variable.
  • Get the maximum value of the given list using the built-in max() function and store it in another variable.
  • Print the maximum value of the above-given List.
  • Get the position of the maximum value of the given List using the built-in index() function and store it in another variable.
  • Print the position of the maximum value of the given List i.e. maximum position+1( since list index starts from zero).
  • The Exit of the program.

Below is the implementation:

#Give the list as User input using list(),map(),input(),and split() functions and store it in a variable.
Gvn_lst = list(map(int, input('Enter some random List Elements separated by spaces = ').split()))
# Get the maximum value of the given list using the built-in max() function and
# store it in another variable
maxim_vle = max(Gvn_lst)
# Print the maximum value of the above given List.
print("Maximum Value in the above Given list = ", maxim_vle)
# Get the position of the maximum value of the List using the built-in index() function
# and store it in another variable.
maxim_positn = Gvn_lst.index(maxim_vle)
# Print the position of the maximum value of the given List i.e. maximum position+1
# ( since list index starts from zero).
print("Position of Maximum value of the above Given List = ", maxim_positn+1)

Output:

Enter some random List Elements separated by spaces = 4 3 7 1 2 8 9
Maximum Value in the above Given list = 9
Position of Maximum value of the above Given List = 7

Here we printed the index of the maximum element of the given list.

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Pattern program in python – Python Program to Print an Inverted Star Pattern | Python code to create an inverted Pyramid start pattern

Program to Print an Inverted Star Pattern

Pattern program in python: Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Python Program to Print the pattern of an Inverted Star: Given a number, the task is to print an Inverted Star Pattern in Python. In our python programming articles, you can also learn how to print a program of Inverted pyramid pattern and print inverted pyramid star pattern in python language.

Let’s see the examples of python program to print inverted star pattern from here

Example1:

Input:

given rows = 8

Output:

********
 *******
  ******
   *****
    ****
     ***
      **
       *

Example2:

Input:

given rows=10

Output:

**********
 *********
  ********
   *******
    ******
     *****
      ****
       ***
        **
         *

Here is the program to print Inverted Star Pattern:

# python 3 code to print inverted star
# pattern 
  
# n is the number of rows in which
# star is going to be printed.
n=11
  
# i is going to be enabled to
# range between n-i t 0 with a
# decrement of 1 with each iteration.
# and in print function, for each iteration,
# ” ” is multiplied with n-i and ‘*’ is
# multiplied with i to create correct
# space before of the stars.
for i in range (n, 0, -1):
    print((n-i) * ' ' + i * '*')

python 3 code to print inverted star pattern

Program to Print an Inverted Star Pattern in Python

Below are the ways to print an Inverted Star Pattern in  Python :

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)Using for loop printing the inverted star pattern in Python(Static Input)

Using for loop printing the inverted star pattern in Python(Static Input)

Approach:

  • Give the number as static and store it in a variable
  • Use a for loop in which the value of k varies between n-1 and 0 and is decremented by one with each iteration.
  • Multiply empty spaces by n-i and ‘*’ by k then print both of them.
  • Exit of program.

Below is the implementation:

# given number numb
numb = 8
# Use a for loop in which the value of k varies
# between n-1 and 0 and is decremented by one with each iteration.
for k in range(numb, 0, -1):
  # Multiply empty spaces by n-i and '*' by k then print both of them.
    print((numb-k) * ' ' + k * '*')

Output:

********
 *******
  ******
   *****
    ****
     ***
      **
       *

Explanation:

  • Give the number as static and stored it in  a variable numb
  • The for loop allows I to range between n-1 and 0, with each iteration decrementing by one.
  • To maintain proper star spacing, ” ” is multiplied by n-i and ‘*’ is multiplied by I for each iteration.
  • The requisite pattern has been printed.

2)Using for loop printing the inverted star pattern in Python(User Input)

Using for loop printing the inverted star pattern in Python(User Input)

Approach:

  • Scan the given number using int(input()) and store it in a variable.
  • Use a for loop in which the value of k varies between n-1 and 0 and is decremented by one with each iteration.
  • Multiply empty spaces by n-i and ‘*’ by k then print both of them.
  • Exit of program.

Below is the implementation:

# given number numb
numb = int(input("enter the number of rows required = "))
# Use a for loop in which the value of k varies
# between n-1 and 0 and is decremented by one with each iteration.
for k in range(numb, 0, -1):
  # Multiply empty spaces by n-i and '*' by k then print both of them.
    print((numb-k) * ' ' + k * '*')

Output:

enter the number of rows required = 10
**********
 *********
  ********
   *******
    ******
     *****
      ****
       ***
        **
         *

3)Using while loop printing the inverted star pattern in Python(Static Input)

Using while loop printing the inverted star pattern in Python(Static Input)

Approach:

  • Give the number as static and store it in a variable
  • Using while loop iterate till number is greater than 0.
  • Multiply empty spaces by tem-i and ‘*’ by numb then print both of them.
  • Decrement the number by 1.
  • The Exit of the program.

Below is the implementation:

# given number numb
numb = 10
# Make a duplicate of the integer by storing it in a variable
tem = numb
# Use a for loop in which the value of k varies
# between n-1 and 0 and is decremented by one with each iteration.
while(numb > 0):
  # Multiply empty spaces by n-i and '*' by k then print both of them.
    print((tem-numb) * ' ' + numb * '*')
    # decrement the number by 1
    numb = numb-1

Output:

**********
 *********
  ********
   *******
    ******
     *****
      ****
       ***
        **
         *

4)Using while loop printing the inverted star pattern in Python(User Input)

Using while loop printing the inverted star pattern in Python(User Input)

Approach:

  • Scan the given number using int(input()) and store it in a variable.
  • Using while loop iterate till number is greater than 0.
  • Multiply empty spaces by tem-i and ‘*’ by numb then print both of them.
  • Decrement the number by 1.
  • Exit of program.

Below is the implementation:

# given number numb
numb = int(input("enter the number of rows required = "))
# Make a duplicate of the integer by storing it in a variable
tem = numb
# Use a for loop in which the value of k varies
# between n-1 and 0 and is decremented by one with each iteration.
while(numb > 0):
  # Multiply empty spaces by n-i and '*' by k then print both of them.
    print((tem-numb) * ' ' + numb * '*')
    # decrement the number by 1
    numb = numb-1

Output:

enter the number of rows required = 10
**********
 *********
  ********
   *******
    ******
     *****
      ****
       ***
        **
         *

Programs to print inverted half pyramid using *

This instance is similar to an upright pyramid but that here we begin from the total number of rows and in each iteration, we decrease the number of rows by 1.

Programs to print inverted half pyramid using star

Source Code:

rows = int(input("Enter number of rows: "))

for i in range(rows, 0, -1):
    for j in range(0, i):
        print("* ", end=" ")
    
    print("\n")

output: 

* * * * *
* * * *
* * *
* *
*

Related Programs:

Python zip multiple files – Python: How to create a zip archive from multiple files or Directory

Method to create zip archive from multiple files or directory in python

Python zip multiple files: In this article, we discuss how we can create a zip archive of multiple files or directories in python. To understand this let us understand about ZipFile class.

ZipFile class

Create zip file python: To execute this program we have to import ZipFile class of zipfile module.ZipFile is a class of zipfile modules for reading and writing zip files.

syntax: zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, compresslevel=None, *, strict_timestamps=True)

Create a zip archives of multiples file

    • Method 1:Without using with statement

Let us first write the program and then see how code works.

from zipfile import ZipFile
# create a ZipFile object
zipObj = ZipFile('sample.zip', 'w')
# Add multiple files to the zip
zipObj.write('file1.txt')
zipObj.write('file2.txt')
# close the Zip File
zipObj.close()

Output

Directory structure before the execution of the program

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10-06-2021 18:41 14 file1.txt
-a---- 10-06-2021 18:41 15 file2.txt
-a---- 10-06-2021 19:06 216 zip.py

Directory structure after the execution of the program

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10-06-2021 18:41 14 file1.txt
-a---- 10-06-2021 18:41 15 file2.txt
-a---- 10-06-2021 19:09 239 sample.zip
-a---- 10-06-2021 19:09 216 zip.py

Here we clearly see that a zip file is created.

Let see how the program works. First, we create a ZipFile object bypassing the new file name and mode as ‘w’ (write mode). It will create a new zip file and open it within the ZipFile object. Then we use Call write() function on ZipFile object to add the files in it and then call close() on ZipFile object to Close the zip file.

  • Method 2:Using with statement

Python create zip file: The difference between this and the previous method is that when we didn’t use with the statement then we have to close the zip file when the ZipFile object goes out of scope but when we use with statement the zip file automatically close when the ZipFile object goes out of scope. Let see the code for this.

from zipfile import ZipFile
# Create a ZipFile Object
with ZipFile('sample2.zip', 'w') as zipObj:
   # Add multiple files to the zip
   zipObj.write('file1.txt')
   zipObj.write('file2.txt')

Output

Directory structure before the execution of the program

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10-06-2021 18:41 14 file1.txt
-a---- 10-06-2021 18:41 15 file2.txt
-a---- 10-06-2021 19:09 239 sample.zip
-a---- 10-06-2021 19:21 429 zip.py

Directory structure after the execution of the program

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10-06-2021 18:41 14 file1.txt
-a---- 10-06-2021 18:41 15 file2.txt
-a---- 10-06-2021 19:09 239 sample.zip
-a---- 10-06-2021 19:24 239 sample2.zip
-a---- 10-06-2021 19:24 429 zip.py

Here we see that another zip file is created.

Create a zip archive of the directory

Python zip directory: To zip selected files from a directory we need to check the condition on each file path while iteration before adding it to the zip file. As here we work on directory and file so we also have to import os module. Let see the code for this.

from zipfile import ZipFile
import os
from os.path import basename
# create a ZipFile object
dirName="../zip"
with ZipFile('sampleDir.zip', 'w') as zipObj:
   # Iterate over all the files in directory
   for folderName, subfolders, filenames in os.walk(dirName):
       for filename in filenames:
           #create complete filepath of file in directory
           filePath = os.path.join(folderName, filename)
           # Add file to zip
           zipObj.write(filePath, basename(filePath))

Output

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10-06-2021 18:41 14 file1.txt
-a---- 10-06-2021 18:41 15 file2.txt
-a---- 10-06-2021 19:09 239 sample.zip
-a---- 10-06-2021 19:24 239 sample2.zip
-a---- 10-06-2021 21:44 2796 sampleDir.zip
-a---- 10-06-2021 19:24 429 zip.py
-a---- 10-06-2021 21:44 506 zipdir.py

Here we see that the sampleDir.zip file is created.

Pandas read csv delimeter – Read Csv File to Dataframe With Custom Delimiter in Python

Different methods to read CSV files with custom delimiter in python

Pandas read csv delimeter: In this article, we will see what are CSV files, how to use them in pandas, and then we see how and why to use custom delimiter with CSV files in pandas.

CSV file

Pandas read csv separator: A simple way to store big data sets is to use CSV files (comma-separated files).CSV files contain plain text and is a well know format that can be read by everyone including Pandas. Generally, CSV files contain columns separated by commas, but they can also contain content separated by a tab, or underscore or hyphen, etc. Generally, CSV files look like this:-

total_bill,tip,sex,smoker,day,time,size
16.99,1.01,Female,No,Sun,Dinner,2
10.34,1.66,Male,No,Sun,Dinner,3
21.01,3.5,Male,No,Sun,Dinner,3
23.68,3.31,Male,No,Sun,Dinner,2
24.59,3.61,Female,No,Sun,Dinner,4

Here we see different columns and their values are separated by commas.

Use CSV file in pandas

Read csv separator: read_csv() method is used to import and read CSV files in pandas. After this step, a CSV file act as a normal dataframe and we can use operation in CSV file as we use in dataframe.

syntax:  pandas.read_csv(filepath_or_buffer, sep=‘, ‘, delimiter=None, header=‘infer’, names=None, index_col=None, ….)

',' is default separator in read_csv() method.

Let see this with an example

import pandas as pd
data=pd.read_csv('example1.csv')
data.head()

Output

total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4

Why use separator or delimiter with read_csv() method

Read_csv separator: Till now we understand that generally, CSV files contain data separated data that is separated by comma but sometimes it can contain data separated by tab or hyphen, etc. So to handle this we use a seperator. Let understand this with the help of an example. Suppose we have a CSV file separated by an underscore and we try to read that CSV file without using a separator or with using default separator i.e. comma. So let see what happens in this case.

"total_bill"_tip_sex_smoker_day_time_size
16.99_1.01_Female_No_Sun_Dinner_2
10.34_1.66_Male_No_Sun_Dinner_3
21.01_3.5_Male_No_Sun_Dinner_3
23.68_3.31_Male_No_Sun_Dinner_2
24.59_3.61_Female_No_Sun_Dinner_4
25.29_4.71_Male_No_Sun_Dinner_4
8.77_2_Male_No_Sun_Dinner_2

Suppose this is our CSV file separated by an underscore.

total_bill_tip_sex_smoker_day_time_size
0 16.99_1.01_Female_No_Sun_Dinner_2
1 10.34_1.66_Male_No_Sun_Dinner_3
2 21.01_3.5_Male_No_Sun_Dinner_3
3 23.68_3.31_Male_No_Sun_Dinner_2
4 24.59_3.61_Female_No_Sun_Dinner_4

Now see when we didn’t use a default separator here how unordered our data look like. So to solve this issue we use Separator. Now we will see when we use a separator to underscore how we get the same data in an ordered manner.

import pandas as pd 
data=pd.read_csv('example2.csv',sep = '_',engine = 'python') 
data.head()

Output

total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4

So this example is sufficient to understand why there is a need of using a separator of delimiter in pandas while working on a CSV file.

Now suppose there is a CSV file in while data is separated by multiple separators. For example:-

totalbill_tip,sex:smoker,day_time,size
16.99,1.01:Female|No,Sun,Dinner,2
10.34,1.66,Male,No|Sun:Dinner,3
21.01:3.5_Male,No:Sun,Dinner,3
23.68,3.31,Male|No,Sun_Dinner,2
24.59:3.61,Female_No,Sun,Dinner,4
25.29,4.71|Male,No:Sun,Dinner,4

Here we see there are multiple seperator used. So here we can not use any custom delimiter. To solve this problem regex or regular expression is used. Let see with the help of an example.

import pandas as pd 
data=pd.read_csv('example4.csv',sep = '[:, |_]') 
data.head()

Output

totalbill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4

When we notice we pass a list of separators in the sep parameter that is contained in our CSV file.

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.