Description
stringlengths
9
105
Link
stringlengths
45
135
Code
stringlengths
10
26.8k
Test_Case
stringlengths
9
202
Merge
stringlengths
63
27k
Create a Pandas DataFrame from List of Dicts
https://www.geeksforgeeks.org/create-a-pandas-dataframe-from-list-of-dicts/
import pandas as pd # Initialise data to lists. data = [ {"Geeks": "dataframe", "For": "using", "geeks": "list"}, {"Geeks": 10, "For": 20, "geeks": 30}, ] # With two column indices, values same # as dictionary keys df1 = pd.DataFrame(data, index=["ind1", "ind2"], columns=["Geeks", "For"]) # With two column indices with # one index with other name df2 = pd.DataFrame(data, index=["indx", "indy"]) # print for first data frame print(df1, "\n") # Print for second DataFrame. print(df2)
#Output : Geeks For geeks
Create a Pandas DataFrame from List of Dicts import pandas as pd # Initialise data to lists. data = [ {"Geeks": "dataframe", "For": "using", "geeks": "list"}, {"Geeks": 10, "For": 20, "geeks": 30}, ] # With two column indices, values same # as dictionary keys df1 = pd.DataFrame(data, index=["ind1", "ind2"], columns=["Geeks", "For"]) # With two column indices with # one index with other name df2 = pd.DataFrame(data, index=["indx", "indy"]) # print for first data frame print(df1, "\n") # Print for second DataFrame. print(df2) #Output : Geeks For geeks [END]
Python | Convert list of nested dictionary into Pandas dataframe
https://www.geeksforgeeks.org/python-convert-list-of-nested-dictionary-into-pandas-dataframe/
# importing pandas import pandas as pd # List of nested dictionary initialization list = [ { "Student": [ {"Exam": 90, "Grade": "a"}, {"Exam": 99, "Grade": "b"}, {"Exam": 97, "Grade": "c"}, ], "Name": "Paras Jain", }, { "Student": [{"Exam": 89, "Grade": "a"}, {"Exam": 80, "Grade": "b"}], "Name": "Chunky Pandey", }, ] # print(list)
#Output : Name Maths Physics Chemistry
Python | Convert list of nested dictionary into Pandas dataframe # importing pandas import pandas as pd # List of nested dictionary initialization list = [ { "Student": [ {"Exam": 90, "Grade": "a"}, {"Exam": 99, "Grade": "b"}, {"Exam": 97, "Grade": "c"}, ], "Name": "Paras Jain", }, { "Student": [{"Exam": 89, "Grade": "a"}, {"Exam": 80, "Grade": "b"}], "Name": "Chunky Pandey", }, ] # print(list) #Output : Name Maths Physics Chemistry [END]
Python | Convert list of nested dictionary into Pandas dataframe
https://www.geeksforgeeks.org/python-convert-list-of-nested-dictionary-into-pandas-dataframe/
# rows list initialization rows = [] # appending rows for data in list: data_row = data["Student"] time = data["Name"] for row in data_row: row["Name"] = time rows.append(row) # using data frame df = pd.DataFrame(rows) # print(df)
#Output : Name Maths Physics Chemistry
Python | Convert list of nested dictionary into Pandas dataframe # rows list initialization rows = [] # appending rows for data in list: data_row = data["Student"] time = data["Name"] for row in data_row: row["Name"] = time rows.append(row) # using data frame df = pd.DataFrame(rows) # print(df) #Output : Name Maths Physics Chemistry [END]
Python | Convert list of nested dictionary into Pandas dataframe
https://www.geeksforgeeks.org/python-convert-list-of-nested-dictionary-into-pandas-dataframe/
# using pivot_table df = df.pivot_table(index="Name", columns=["Grade"], values=["Exam"]).reset_index() # Defining columns df.columns = ["Name", "Maths", "Physics", "Chemistry"] # print dataframe print(df)
#Output : Name Maths Physics Chemistry
Python | Convert list of nested dictionary into Pandas dataframe # using pivot_table df = df.pivot_table(index="Name", columns=["Grade"], values=["Exam"]).reset_index() # Defining columns df.columns = ["Name", "Maths", "Physics", "Chemistry"] # print dataframe print(df) #Output : Name Maths Physics Chemistry [END]
Python | Convert list of nested dictionary into Pandas dataframe
https://www.geeksforgeeks.org/python-convert-list-of-nested-dictionary-into-pandas-dataframe/
# Python program to convert list of nested # dictionary into Pandas dataframe # importing pandas import pandas as pd # List of list of dictionary initialization list = [ { "Student": [ {"Exam": 90, "Grade": "a"}, {"Exam": 99, "Grade": "b"}, {"Exam": 97, "Grade": "c"}, ], "Name": "Paras Jain", }, { "Student": [{"Exam": 89, "Grade": "a"}, {"Exam": 80, "Grade": "b"}], "Name": "Chunky Pandey", }, ] # rows list initialization rows = [] # appending rows for data in list: data_row = data["Student"] time = data["Name"] for row in data_row: row["Name"] = time rows.append(row) # using data frame df = pd.DataFrame(rows) # using pivot_table df = df.pivot_table(index="Name", columns=["Grade"], values=["Exam"]).reset_index() # Defining columns df.columns = ["Name", "Maths", "Physics", "Chemistry"] # print dataframe print(df)
#Output : Name Maths Physics Chemistry
Python | Convert list of nested dictionary into Pandas dataframe # Python program to convert list of nested # dictionary into Pandas dataframe # importing pandas import pandas as pd # List of list of dictionary initialization list = [ { "Student": [ {"Exam": 90, "Grade": "a"}, {"Exam": 99, "Grade": "b"}, {"Exam": 97, "Grade": "c"}, ], "Name": "Paras Jain", }, { "Student": [{"Exam": 89, "Grade": "a"}, {"Exam": 80, "Grade": "b"}], "Name": "Chunky Pandey", }, ] # rows list initialization rows = [] # appending rows for data in list: data_row = data["Student"] time = data["Name"] for row in data_row: row["Name"] = time rows.append(row) # using data frame df = pd.DataFrame(rows) # using pivot_table df = df.pivot_table(index="Name", columns=["Grade"], values=["Exam"]).reset_index() # Defining columns df.columns = ["Name", "Maths", "Physics", "Chemistry"] # print dataframe print(df) #Output : Name Maths Physics Chemistry [END]
Creating a dataframe from Pandas series
https://www.geeksforgeeks.org/creating-a-dataframe-from-pandas-series/
# importing pandas library import pandas as pd # Creating a list author = ["Jitender", "Purnima", "Arpit", "Jyoti"] # Creating a Series by passing list # variable to Series() function auth_series = pd.Series(author) # Printing Series print(auth_series)
#Output : 0 Jitender
Creating a dataframe from Pandas series # importing pandas library import pandas as pd # Creating a list author = ["Jitender", "Purnima", "Arpit", "Jyoti"] # Creating a Series by passing list # variable to Series() function auth_series = pd.Series(author) # Printing Series print(auth_series) #Output : 0 Jitender [END]
Creating a dataframe from Pandas series
https://www.geeksforgeeks.org/creating-a-dataframe-from-pandas-series/
print(type(auth_series))
#Output : 0 Jitender
Creating a dataframe from Pandas series print(type(auth_series)) #Output : 0 Jitender [END]
Creating a dataframe from Pandas series
https://www.geeksforgeeks.org/creating-a-dataframe-from-pandas-series/
# Importing Pandas library import pandas as pd # Creating two lists author = ["Jitender", "Purnima", "Arpit", "Jyoti"] article = [210, 211, 114, 178] # Creating two Series by passing lists auth_series = pd.Series(author) article_series = pd.Series(article) # Creating a dictionary by passing Series objects as values frame = {"Author": auth_series, "Article": article_series} # Creating DataFrame by passing Dictionary result = pd.DataFrame(frame) # Printing elements of Dataframe print(result)
#Output : 0 Jitender
Creating a dataframe from Pandas series # Importing Pandas library import pandas as pd # Creating two lists author = ["Jitender", "Purnima", "Arpit", "Jyoti"] article = [210, 211, 114, 178] # Creating two Series by passing lists auth_series = pd.Series(author) article_series = pd.Series(article) # Creating a dictionary by passing Series objects as values frame = {"Author": auth_series, "Article": article_series} # Creating DataFrame by passing Dictionary result = pd.DataFrame(frame) # Printing elements of Dataframe print(result) #Output : 0 Jitender [END]
Creating a dataframe from Pandas series
https://www.geeksforgeeks.org/creating-a-dataframe-from-pandas-series/
# Importing pandas library import pandas as pd # Creating Series auth_series = pd.Series(["Jitender", "Purnima", "Arpit", "Jyoti"]) article_series = pd.Series([210, 211, 114, 178]) # Creating Dictionary frame = {"Author": auth_series, "Article": article_series} # Creating Dataframe result = pd.DataFrame(frame) # Creating another list age = [21, 21, 24, 23] # Creating new column in the dataframe by # providing s Series created using list result["Age"] = pd.Series(age) # Printing dataframe print(result)
#Output : 0 Jitender
Creating a dataframe from Pandas series # Importing pandas library import pandas as pd # Creating Series auth_series = pd.Series(["Jitender", "Purnima", "Arpit", "Jyoti"]) article_series = pd.Series([210, 211, 114, 178]) # Creating Dictionary frame = {"Author": auth_series, "Article": article_series} # Creating Dataframe result = pd.DataFrame(frame) # Creating another list age = [21, 21, 24, 23] # Creating new column in the dataframe by # providing s Series created using list result["Age"] = pd.Series(age) # Printing dataframe print(result) #Output : 0 Jitender [END]
Creating a dataframe from Pandas series
https://www.geeksforgeeks.org/creating-a-dataframe-from-pandas-series/
# Importing pandas library import pandas as pd # Creating Series auth_series = pd.Series(["Jitender", "Purnima", "Arpit", "Jyoti"]) article_series = pd.Series([210, 211, 114, 178]) # Creating Dictionary frame = {"Author": auth_series, "Article": article_series} # Creating Dataframe result = pd.DataFrame(frame) # Creating another list age = [21, 21, 24] # Creating new column in the dataframe by # providing s Series created using list result["Age"] = pd.Series(age) # Printing dataframe print(result)
#Output : 0 Jitender
Creating a dataframe from Pandas series # Importing pandas library import pandas as pd # Creating Series auth_series = pd.Series(["Jitender", "Purnima", "Arpit", "Jyoti"]) article_series = pd.Series([210, 211, 114, 178]) # Creating Dictionary frame = {"Author": auth_series, "Article": article_series} # Creating Dataframe result = pd.DataFrame(frame) # Creating another list age = [21, 21, 24] # Creating new column in the dataframe by # providing s Series created using list result["Age"] = pd.Series(age) # Printing dataframe print(result) #Output : 0 Jitender [END]
Creating a dataframe from Pandas series
https://www.geeksforgeeks.org/creating-a-dataframe-from-pandas-series/
# Importing pandas library import pandas as pd # Creating dictionary of Series dict1 = { "Auth_Name": pd.Series(["Jitender", "Purnima", "Arpit", "Jyoti"]), "Author_Book_No": pd.Series([210, 211, 114, 178]), "Age": pd.Series([21, 21, 24, 23]), } # Creating Dataframe df = pd.DataFrame(dict1) # Printing dataframe print(df)
#Output : 0 Jitender
Creating a dataframe from Pandas series # Importing pandas library import pandas as pd # Creating dictionary of Series dict1 = { "Auth_Name": pd.Series(["Jitender", "Purnima", "Arpit", "Jyoti"]), "Author_Book_No": pd.Series([210, 211, 114, 178]), "Age": pd.Series([21, 21, 24, 23]), } # Creating Dataframe df = pd.DataFrame(dict1) # Printing dataframe print(df) #Output : 0 Jitender [END]
Creating a dataframe from Pandas series
https://www.geeksforgeeks.org/creating-a-dataframe-from-pandas-series/
# Importing pandas library import pandas as pd # Creating dictionary of Series dict1 = { "Auth_Name": pd.Series(["Jitender", "Purnima", "Arpit", "Jyoti"]), "Author_Book_No": pd.Series([210, 211, 114, 178]), "Age": pd.Series([21, 21, 24, 23]), } # Creating Dataframe df = pd.DataFrame(dict1, index=["SNo1", "SNo2", "SNo3", "SNo4"]) # Printing dataframe print(df)
#Output : 0 Jitender
Creating a dataframe from Pandas series # Importing pandas library import pandas as pd # Creating dictionary of Series dict1 = { "Auth_Name": pd.Series(["Jitender", "Purnima", "Arpit", "Jyoti"]), "Author_Book_No": pd.Series([210, 211, 114, 178]), "Age": pd.Series([21, 21, 24, 23]), } # Creating Dataframe df = pd.DataFrame(dict1, index=["SNo1", "SNo2", "SNo3", "SNo4"]) # Printing dataframe print(df) #Output : 0 Jitender [END]
Creating a dataframe from Pandas series
https://www.geeksforgeeks.org/creating-a-dataframe-from-pandas-series/
# This code is provided by Sheetal Verma # Importing pandas library import pandas as pd # Creating dictionary of Series dict1 = { "Auth_Name": pd.Series( ["Jitender", "Purnima", "Arpit", "Jyoti"], index=["SNo1", "SNo2", "SNo3", "SNo4"], ), "Author_Book_No": pd.Series( [210, 211, 114, 178], index=["SNo1", "SNo2", "SNo3", "SNo4"] ), "Age": pd.Series([21, 21, 24, 23], index=["SNo1", "SNo2", "SNo3", "SNo4"]), } # Creating Dataframe df = pd.DataFrame(dict1, index=["SNo1", "SNo2", "SNo3", "SNo4"]) # Printing dataframe print(df)
#Output : 0 Jitender
Creating a dataframe from Pandas series # This code is provided by Sheetal Verma # Importing pandas library import pandas as pd # Creating dictionary of Series dict1 = { "Auth_Name": pd.Series( ["Jitender", "Purnima", "Arpit", "Jyoti"], index=["SNo1", "SNo2", "SNo3", "SNo4"], ), "Author_Book_No": pd.Series( [210, 211, 114, 178], index=["SNo1", "SNo2", "SNo3", "SNo4"] ), "Age": pd.Series([21, 21, 24, 23], index=["SNo1", "SNo2", "SNo3", "SNo4"]), } # Creating Dataframe df = pd.DataFrame(dict1, index=["SNo1", "SNo2", "SNo3", "SNo4"]) # Printing dataframe print(df) #Output : 0 Jitender [END]
Mapping external values to dataframe values in Pandas
https://www.geeksforgeeks.org/mapping-external-values-to-dataframe-values-in-pandas/
# Creating new dataframe import pandas as pd initial_data = { "First_name": ["Ram", "Mohan", "Tina", "Jeetu", "Meera"], "Last_name": ["Kumar", "Sharma", "Ali", "Gandhi", "Kumari"], "Age": [42, 52, 36, 21, 23], "City": ["Mumbai", "Noida", "Pune", "Delhi", "Bihar"], } df = pd.DataFrame(initial_data, columns=["First_name", "Last_name", "Age", "City"]) # Create new column using dictionary new_data = { "Ram": "B.Com", "Mohan": "IAS", "Tina": "LLB", "Jeetu": "B.Tech", "Meera": "MBBS", } # combine this new data with existing DataFrame df["Qualification"] = df["First_name"].map(new_data) print(df)
#Output :
Mapping external values to dataframe values in Pandas # Creating new dataframe import pandas as pd initial_data = { "First_name": ["Ram", "Mohan", "Tina", "Jeetu", "Meera"], "Last_name": ["Kumar", "Sharma", "Ali", "Gandhi", "Kumari"], "Age": [42, 52, 36, 21, 23], "City": ["Mumbai", "Noida", "Pune", "Delhi", "Bihar"], } df = pd.DataFrame(initial_data, columns=["First_name", "Last_name", "Age", "City"]) # Create new column using dictionary new_data = { "Ram": "B.Com", "Mohan": "IAS", "Tina": "LLB", "Jeetu": "B.Tech", "Meera": "MBBS", } # combine this new data with existing DataFrame df["Qualification"] = df["First_name"].map(new_data) print(df) #Output : [END]
Mapping external values to dataframe values in Pandas
https://www.geeksforgeeks.org/mapping-external-values-to-dataframe-values-in-pandas/
# Creating new dataframe import pandas as pd initial_data = { "First_name": ["Ram", "Mohan", "Tina", "Jeetu", "Meera"], "Last_name": ["Kumar", "Sharma", "Ali", "Gandhi", "Kumari"], "Age": [42, 52, 36, 21, 23], "City": ["Mumbai", "Noida", "Pune", "Delhi", "Bihar"], } df = pd.DataFrame(initial_data, columns=["First_name", "Last_name", "Age", "City"]) # Create new column using dictionary new_data = {"Ram": "Shyam", "Tina": "Riya", "Jeetu": "Jitender"} print(df, end="\n\n") # combine this new data with existing DataFrame df = df.replace({"First_name": new_data}) print(df)
#Output :
Mapping external values to dataframe values in Pandas # Creating new dataframe import pandas as pd initial_data = { "First_name": ["Ram", "Mohan", "Tina", "Jeetu", "Meera"], "Last_name": ["Kumar", "Sharma", "Ali", "Gandhi", "Kumari"], "Age": [42, 52, 36, 21, 23], "City": ["Mumbai", "Noida", "Pune", "Delhi", "Bihar"], } df = pd.DataFrame(initial_data, columns=["First_name", "Last_name", "Age", "City"]) # Create new column using dictionary new_data = {"Ram": "Shyam", "Tina": "Riya", "Jeetu": "Jitender"} print(df, end="\n\n") # combine this new data with existing DataFrame df = df.replace({"First_name": new_data}) print(df) #Output : [END]
Mapping external values to dataframe values in Pandas
https://www.geeksforgeeks.org/mapping-external-values-to-dataframe-values-in-pandas/
# Creating new dataframe import pandas as pd initial_data = { "First_name": ["Ram", "Mohan", "Tina", "Jeetu", "Meera"], "Last_name": ["Kumar", "Sharma", "Ali", "Gandhi", "Kumari"], "Age": [42, 52, 36, 21, 23], "City": ["Mumbai", "Noida", "Pune", "Delhi", "Bihar"], } df = pd.DataFrame(initial_data, columns=["First_name", "Last_name", "Age", "City"]) # Create new column using dictionary new_data = {0: "Shyam", 2: "Riya", 3: "Jitender"} # combine this new data with existing DataFrame df["First_name"].update(pd.Series(new_data)) print(df)
#Output :
Mapping external values to dataframe values in Pandas # Creating new dataframe import pandas as pd initial_data = { "First_name": ["Ram", "Mohan", "Tina", "Jeetu", "Meera"], "Last_name": ["Kumar", "Sharma", "Ali", "Gandhi", "Kumari"], "Age": [42, 52, 36, 21, 23], "City": ["Mumbai", "Noida", "Pune", "Delhi", "Bihar"], } df = pd.DataFrame(initial_data, columns=["First_name", "Last_name", "Age", "City"]) # Create new column using dictionary new_data = {0: "Shyam", 2: "Riya", 3: "Jitender"} # combine this new data with existing DataFrame df["First_name"].update(pd.Series(new_data)) print(df) #Output : [END]
How to iterate over rows in Pandas Dataframe
https://www.geeksforgeeks.org/how-to-iterate-over-rows-in-pandas-dataframe/
# importing pandas import pandas as pd # list of dicts input_df = [ {"name": "Sujeet", "age": 10}, {"name": "Sameer", "age": 11}, {"name": "Sumit", "age": 12}, ] df = pd.DataFrame(input_df) print("Original DataFrame: \n", df) print("\nRows iterated using iterrows() : ") for index, row in df.iterrows(): print(row["name"], row["age"])
#Output : Original DataFrame:
How to iterate over rows in Pandas Dataframe # importing pandas import pandas as pd # list of dicts input_df = [ {"name": "Sujeet", "age": 10}, {"name": "Sameer", "age": 11}, {"name": "Sumit", "age": 12}, ] df = pd.DataFrame(input_df) print("Original DataFrame: \n", df) print("\nRows iterated using iterrows() : ") for index, row in df.iterrows(): print(row["name"], row["age"]) #Output : Original DataFrame: [END]
How to iterate over rows in Pandas Dataframe
https://www.geeksforgeeks.org/how-to-iterate-over-rows-in-pandas-dataframe/
# importing pandas import pandas as pd # list of dicts input_df = [ {"name": "Sujeet", "age": 10}, {"name": "Sameer", "age": 110}, {"name": "Sumit", "age": 120}, ] df = pd.DataFrame(input_df) print("Original DataFrame: \n", df) print("\nRows iterated using itertuples() : ") for row in df.itertuples(): print(getattr(row, "name"), getattr(row, "age"))
#Output : Original DataFrame:
How to iterate over rows in Pandas Dataframe # importing pandas import pandas as pd # list of dicts input_df = [ {"name": "Sujeet", "age": 10}, {"name": "Sameer", "age": 110}, {"name": "Sumit", "age": 120}, ] df = pd.DataFrame(input_df) print("Original DataFrame: \n", df) print("\nRows iterated using itertuples() : ") for row in df.itertuples(): print(getattr(row, "name"), getattr(row, "age")) #Output : Original DataFrame: [END]
Different ways to iterate over rows in Pandas Dataframe
https://www.geeksforgeeks.org/different-ways-to-iterate-over-rows-in-pandas-dataframe/
# import pandas package as pd import pandas as pd # Define a dictionary containing students data data = { "Name": ["Ankit", "Amit", "Aishwarya", "Priyanka"], "Age": [21, 19, 20, 18], "Stream": ["Math", "Commerce", "Arts", "Biology"], "Percentage": [88, 92, 95, 70], } # Convert the dictionary into DataFrame df = pd.DataFrame(data, columns=["Name", "Age", "Stream", "Percentage"]) print("Given Dataframe :\n", df) print("\nIterating over rows using index attribute :\n") # iterate through each row and select # 'Name' and 'Stream' column respectively. for ind in df.index: print(df["Name"][ind], df["Stream"][ind])
#Output : Given Dataframe :
Different ways to iterate over rows in Pandas Dataframe # import pandas package as pd import pandas as pd # Define a dictionary containing students data data = { "Name": ["Ankit", "Amit", "Aishwarya", "Priyanka"], "Age": [21, 19, 20, 18], "Stream": ["Math", "Commerce", "Arts", "Biology"], "Percentage": [88, 92, 95, 70], } # Convert the dictionary into DataFrame df = pd.DataFrame(data, columns=["Name", "Age", "Stream", "Percentage"]) print("Given Dataframe :\n", df) print("\nIterating over rows using index attribute :\n") # iterate through each row and select # 'Name' and 'Stream' column respectively. for ind in df.index: print(df["Name"][ind], df["Stream"][ind]) #Output : Given Dataframe : [END]
Different ways to iterate over rows in Pandas Dataframe
https://www.geeksforgeeks.org/different-ways-to-iterate-over-rows-in-pandas-dataframe/
# import pandas package as pd import pandas as pd # Define a dictionary containing students data data = { "Name": ["Ankit", "Amit", "Aishwarya", "Priyanka"], "Age": [21, 19, 20, 18], "Stream": ["Math", "Commerce", "Arts", "Biology"], "Percentage": [88, 92, 95, 70], } # Convert the dictionary into DataFrame df = pd.DataFrame(data, columns=["Name", "Age", "Stream", "Percentage"]) print("Given Dataframe :\n", df) print("\nIterating over rows using loc function :\n") # iterate through each row and select # 'Name' and 'Age' column respectively. for i in range(len(df)): print(df.loc[i, "Name"], df.loc[i, "Age"])
#Output : Given Dataframe :
Different ways to iterate over rows in Pandas Dataframe # import pandas package as pd import pandas as pd # Define a dictionary containing students data data = { "Name": ["Ankit", "Amit", "Aishwarya", "Priyanka"], "Age": [21, 19, 20, 18], "Stream": ["Math", "Commerce", "Arts", "Biology"], "Percentage": [88, 92, 95, 70], } # Convert the dictionary into DataFrame df = pd.DataFrame(data, columns=["Name", "Age", "Stream", "Percentage"]) print("Given Dataframe :\n", df) print("\nIterating over rows using loc function :\n") # iterate through each row and select # 'Name' and 'Age' column respectively. for i in range(len(df)): print(df.loc[i, "Name"], df.loc[i, "Age"]) #Output : Given Dataframe : [END]
Different ways to iterate over rows in Pandas Dataframe
https://www.geeksforgeeks.org/different-ways-to-iterate-over-rows-in-pandas-dataframe/
# import pandas package as pd import pandas as pd # Define a dictionary containing students data data = { "Name": ["Ankit", "Amit", "Aishwarya", "Priyanka"], "Age": [21, 19, 20, 18], "Stream": ["Math", "Commerce", "Arts", "Biology"], "Percentage": [88, 92, 95, 70], } # Convert the dictionary into DataFrame df = pd.DataFrame(data, columns=["Name", "Age", "Stream", "Percentage"]) print("Given Dataframe :\n", df) print("\nIterating over rows using iloc function :\n") # iterate through each row and select # 0th and 2nd index column respectively. for i in range(len(df)): print(df.iloc[i, 0], df.iloc[i, 2])
#Output : Given Dataframe :
Different ways to iterate over rows in Pandas Dataframe # import pandas package as pd import pandas as pd # Define a dictionary containing students data data = { "Name": ["Ankit", "Amit", "Aishwarya", "Priyanka"], "Age": [21, 19, 20, 18], "Stream": ["Math", "Commerce", "Arts", "Biology"], "Percentage": [88, 92, 95, 70], } # Convert the dictionary into DataFrame df = pd.DataFrame(data, columns=["Name", "Age", "Stream", "Percentage"]) print("Given Dataframe :\n", df) print("\nIterating over rows using iloc function :\n") # iterate through each row and select # 0th and 2nd index column respectively. for i in range(len(df)): print(df.iloc[i, 0], df.iloc[i, 2]) #Output : Given Dataframe : [END]
Different ways to iterate over rows in Pandas Dataframe
https://www.geeksforgeeks.org/different-ways-to-iterate-over-rows-in-pandas-dataframe/
# import pandas package as pd import pandas as pd # Define a dictionary containing students data data = { "Name": ["Ankit", "Amit", "Aishwarya", "Priyanka"], "Age": [21, 19, 20, 18], "Stream": ["Math", "Commerce", "Arts", "Biology"], "Percentage": [88, 92, 95, 70], } # Convert the dictionary into DataFrame df = pd.DataFrame(data, columns=["Name", "Age", "Stream", "Percentage"]) print("Given Dataframe :\n", df) print("\nIterating over rows using iterrows() method :\n") # iterate through each row and select # 'Name' and 'Age' column respectively. for index, row in df.iterrows(): print(row["Name"], row["Age"])
#Output : Given Dataframe :
Different ways to iterate over rows in Pandas Dataframe # import pandas package as pd import pandas as pd # Define a dictionary containing students data data = { "Name": ["Ankit", "Amit", "Aishwarya", "Priyanka"], "Age": [21, 19, 20, 18], "Stream": ["Math", "Commerce", "Arts", "Biology"], "Percentage": [88, 92, 95, 70], } # Convert the dictionary into DataFrame df = pd.DataFrame(data, columns=["Name", "Age", "Stream", "Percentage"]) print("Given Dataframe :\n", df) print("\nIterating over rows using iterrows() method :\n") # iterate through each row and select # 'Name' and 'Age' column respectively. for index, row in df.iterrows(): print(row["Name"], row["Age"]) #Output : Given Dataframe : [END]
Different ways to iterate over rows in Pandas Dataframe
https://www.geeksforgeeks.org/different-ways-to-iterate-over-rows-in-pandas-dataframe/
# import pandas package as pd import pandas as pd # Define a dictionary containing students data data = { "Name": ["Ankit", "Amit", "Aishwarya", "Priyanka"], "Age": [21, 19, 20, 18], "Stream": ["Math", "Commerce", "Arts", "Biology"], "Percentage": [88, 92, 95, 70], } # Convert the dictionary into DataFrame df = pd.DataFrame(data, columns=["Name", "Age", "Stream", "Percentage"]) print("Given Dataframe :\n", df) print("\nIterating over rows using itertuples() method :\n") # iterate through each row and select # 'Name' and 'Percentage' column respectively. for row in df.itertuples(index=True, name="Pandas"): print(getattr(row, "Name"), getattr(row, "Percentage"))
#Output : Given Dataframe :
Different ways to iterate over rows in Pandas Dataframe # import pandas package as pd import pandas as pd # Define a dictionary containing students data data = { "Name": ["Ankit", "Amit", "Aishwarya", "Priyanka"], "Age": [21, 19, 20, 18], "Stream": ["Math", "Commerce", "Arts", "Biology"], "Percentage": [88, 92, 95, 70], } # Convert the dictionary into DataFrame df = pd.DataFrame(data, columns=["Name", "Age", "Stream", "Percentage"]) print("Given Dataframe :\n", df) print("\nIterating over rows using itertuples() method :\n") # iterate through each row and select # 'Name' and 'Percentage' column respectively. for row in df.itertuples(index=True, name="Pandas"): print(getattr(row, "Name"), getattr(row, "Percentage")) #Output : Given Dataframe : [END]
Different ways to iterate over rows in Pandas Dataframe
https://www.geeksforgeeks.org/different-ways-to-iterate-over-rows-in-pandas-dataframe/
# import pandas package as pd import pandas as pd # Define a dictionary containing students data data = { "Name": ["Ankit", "Amit", "Aishwarya", "Priyanka"], "Age": [21, 19, 20, 18], "Stream": ["Math", "Commerce", "Arts", "Biology"], "Percentage": [88, 92, 95, 70], } # Convert the dictionary into DataFrame df = pd.DataFrame(data, columns=["Name", "Age", "Stream", "Percentage"]) print("Given Dataframe :\n", df) print("\nIterating over rows using apply function :\n") # iterate through each row and concatenate # 'Name' and 'Percentage' column respectively. print(df.apply(lambda row: row["Name"] + " " + str(row["Percentage"]), axis=1))
#Output : Given Dataframe :
Different ways to iterate over rows in Pandas Dataframe # import pandas package as pd import pandas as pd # Define a dictionary containing students data data = { "Name": ["Ankit", "Amit", "Aishwarya", "Priyanka"], "Age": [21, 19, 20, 18], "Stream": ["Math", "Commerce", "Arts", "Biology"], "Percentage": [88, 92, 95, 70], } # Convert the dictionary into DataFrame df = pd.DataFrame(data, columns=["Name", "Age", "Stream", "Percentage"]) print("Given Dataframe :\n", df) print("\nIterating over rows using apply function :\n") # iterate through each row and concatenate # 'Name' and 'Percentage' column respectively. print(df.apply(lambda row: row["Name"] + " " + str(row["Percentage"]), axis=1)) #Output : Given Dataframe : [END]
Selementsect any row from a Dataframe using iloc[] and iat[] in Pandas
https://www.geeksforgeeks.org/select-any-row-from-a-dataframe-using-iloc-and-iat-in-pandas/
import pandas as pd # Create the dataframe df = pd.DataFrame( { "Date": ["10/2/2011", "11/2/2011", "12/2/2011", "13/2/11"], "Event": ["Music", "Poetry", "Theatre", "Comedy"], "Cost": [10000, 5000, 15000, 2000], } ) # Create an empty list Row_list = [] # Iterate over each row for i in range((df.shape[0])): # Using iloc to access the values of # the current row denoted by "i" Row_list.append(list(df.iloc[i, :])) # Print the first 3 elements print(Row_list[:3])
#Output : [[10000, '10/2/2011', 'Music'], [5000, '11/2/2011', 'Poetry'],
Selementsect any row from a Dataframe using iloc[] and iat[] in Pandas import pandas as pd # Create the dataframe df = pd.DataFrame( { "Date": ["10/2/2011", "11/2/2011", "12/2/2011", "13/2/11"], "Event": ["Music", "Poetry", "Theatre", "Comedy"], "Cost": [10000, 5000, 15000, 2000], } ) # Create an empty list Row_list = [] # Iterate over each row for i in range((df.shape[0])): # Using iloc to access the values of # the current row denoted by "i" Row_list.append(list(df.iloc[i, :])) # Print the first 3 elements print(Row_list[:3]) #Output : [[10000, '10/2/2011', 'Music'], [5000, '11/2/2011', 'Poetry'], [END]
Selementsect any row from a Dataframe using iloc[] and iat[] in Pandas
https://www.geeksforgeeks.org/select-any-row-from-a-dataframe-using-iloc-and-iat-in-pandas/
# importing pandas as pd import pandas as pd # Create the dataframe df = pd.DataFrame( { "Date": ["10/2/2011", "11/2/2011", "12/2/2011", "13/2/11"], "Event": ["Music", "Poetry", "Theatre", "Comedy"], "Cost": [10000, 5000, 15000, 2000], } ) # Create an empty list Row_list = [] # Iterate over each row for i in range((df.shape[0])): # Create a list to store the data # of the current row cur_row = [] # iterate over all the columns for j in range(df.shape[1]): # append the data of each # column to the list cur_row.append(df.iat[i, j]) # append the current row to the list Row_list.append(cur_row) # Print the first 3 elements print(Row_list[:3])
#Output : [[10000, '10/2/2011', 'Music'], [5000, '11/2/2011', 'Poetry'],
Selementsect any row from a Dataframe using iloc[] and iat[] in Pandas # importing pandas as pd import pandas as pd # Create the dataframe df = pd.DataFrame( { "Date": ["10/2/2011", "11/2/2011", "12/2/2011", "13/2/11"], "Event": ["Music", "Poetry", "Theatre", "Comedy"], "Cost": [10000, 5000, 15000, 2000], } ) # Create an empty list Row_list = [] # Iterate over each row for i in range((df.shape[0])): # Create a list to store the data # of the current row cur_row = [] # iterate over all the columns for j in range(df.shape[1]): # append the data of each # column to the list cur_row.append(df.iat[i, j]) # append the current row to the list Row_list.append(cur_row) # Print the first 3 elements print(Row_list[:3]) #Output : [[10000, '10/2/2011', 'Music'], [5000, '11/2/2011', 'Poetry'], [END]
Limited rows selementsection with given column in Pandas | Python
https://www.geeksforgeeks.org/limited-rows-selection-with-given-column-in-pandas-python/
# Import pandas package import pandas as pd # Define a dictionary containing employee data data = { "Name": ["Jai", "Princi", "Gaurav", "Anuj"], "Age": [27, 24, 22, 32], "Address": ["Delhi", "Kanpur", "Allahabad", "Kannauj"], "Qualification": ["Msc", "MA", "MCA", "Phd"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # select three rows and two columns print(df.loc[1:3, ["Name", "Qualification"]])
#Output : Name Qualification
Limited rows selementsection with given column in Pandas | Python # Import pandas package import pandas as pd # Define a dictionary containing employee data data = { "Name": ["Jai", "Princi", "Gaurav", "Anuj"], "Age": [27, 24, 22, 32], "Address": ["Delhi", "Kanpur", "Allahabad", "Kannauj"], "Qualification": ["Msc", "MA", "MCA", "Phd"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # select three rows and two columns print(df.loc[1:3, ["Name", "Qualification"]]) #Output : Name Qualification [END]
Limited rows selementsection with given column in Pandas | Python
https://www.geeksforgeeks.org/limited-rows-selection-with-given-column-in-pandas-python/
# Import pandas package import pandas as pd # Define a dictionary containing employee data data = { "Name": ["Jai", "Princi", "Gaurav", "Anuj"], "Age": [27, 24, 22, 32], "Address": ["Delhi", "Kanpur", "Allahabad", "Kannauj"], "Qualification": ["Msc", "MA", "MCA", "Phd"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # .loc DataFrame method # filtering rows and selecting columns by label format # df.loc[rows, columns] # row 1, all columns print(df.loc[0, :])
#Output : Name Qualification
Limited rows selementsection with given column in Pandas | Python # Import pandas package import pandas as pd # Define a dictionary containing employee data data = { "Name": ["Jai", "Princi", "Gaurav", "Anuj"], "Age": [27, 24, 22, 32], "Address": ["Delhi", "Kanpur", "Allahabad", "Kannauj"], "Qualification": ["Msc", "MA", "MCA", "Phd"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # .loc DataFrame method # filtering rows and selecting columns by label format # df.loc[rows, columns] # row 1, all columns print(df.loc[0, :]) #Output : Name Qualification [END]
Limited rows selementsection with given column in Pandas | Python
https://www.geeksforgeeks.org/limited-rows-selection-with-given-column-in-pandas-python/
# Import pandas package import pandas as pd # Define a dictionary containing employee data data = { "Name": ["Jai", "Princi", "Gaurav", "Anuj"], "Age": [27, 24, 22, 32], "Address": ["Delhi", "Kanpur", "Allahabad", "Kannauj"], "Qualification": ["Msc", "MA", "MCA", "Phd"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # iloc[row slicing, column slicing] print(df.iloc[0:2, 1:3])
#Output : Name Qualification
Limited rows selementsection with given column in Pandas | Python # Import pandas package import pandas as pd # Define a dictionary containing employee data data = { "Name": ["Jai", "Princi", "Gaurav", "Anuj"], "Age": [27, 24, 22, 32], "Address": ["Delhi", "Kanpur", "Allahabad", "Kannauj"], "Qualification": ["Msc", "MA", "MCA", "Phd"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # iloc[row slicing, column slicing] print(df.iloc[0:2, 1:3]) #Output : Name Qualification [END]
Sorting rows in pandas DataFrame
https://www.geeksforgeeks.org/sorting-rows-in-pandas-dataframe/
# import modules import pandas as pd # create dataframe data = { "name": ["Simon", "Marsh", "Gaurav", "Alex", "Selena"], "Maths": [8, 5, 6, 9, 7], "Science": [7, 9, 5, 4, 7], "English": [7, 4, 7, 6, 8], } df = pd.DataFrame(data) # Sort the dataframe?????????s rows by Science, # in descending order a = df.sort_valu"Science", ascending=0) print("Sorting rows by Science:\n \n", a)
#Output :
Sorting rows in pandas DataFrame # import modules import pandas as pd # create dataframe data = { "name": ["Simon", "Marsh", "Gaurav", "Alex", "Selena"], "Maths": [8, 5, 6, 9, 7], "Science": [7, 9, 5, 4, 7], "English": [7, 4, 7, 6, 8], } df = pd.DataFrame(data) # Sort the dataframe?????????s rows by Science, # in descending order a = df.sort_valu"Science", ascending=0) print("Sorting rows by Science:\n \n", a) #Output : [END]
Sorting rows in pandas DataFrame
https://www.geeksforgeeks.org/sorting-rows-in-pandas-dataframe/
# import modules import pandas as pd # create dataframe data = { "name": ["Simon", "Marsh", "Gaurav", "Alex", "Selena"], "Maths": [8, 5, 6, 9, 7], "Science": [7, 9, 5, 4, 7], "English": [7, 4, 7, 6, 8], } df = pd.DataFrame(data) # Sort the dataframe?????????s rows by Maths # and then by English, in ascending order b = df.sort_value"Maths", "English"]) print("Sort rows by Maths and then by English: \n\n", b)
#Output :
Sorting rows in pandas DataFrame # import modules import pandas as pd # create dataframe data = { "name": ["Simon", "Marsh", "Gaurav", "Alex", "Selena"], "Maths": [8, 5, 6, 9, 7], "Science": [7, 9, 5, 4, 7], "English": [7, 4, 7, 6, 8], } df = pd.DataFrame(data) # Sort the dataframe?????????s rows by Maths # and then by English, in ascending order b = df.sort_value"Maths", "English"]) print("Sort rows by Maths and then by English: \n\n", b) #Output : [END]
Sorting rows in pandas DataFrame
https://www.geeksforgeeks.org/sorting-rows-in-pandas-dataframe/
import pandas as pd # create dataframe data = { "name": ["Simon", "Marsh", "Gaurav", "Alex", "Selena"], "Maths": [8, 5, 6, 9, 7], "Science": [7, 9, 5, 4, 7], "English": [7, 4, 7, 6, 8], } df = pd.DataFrame(data) a = df.sort_values(by="Science", na_position="first") print(a)
#Output :
Sorting rows in pandas DataFrame import pandas as pd # create dataframe data = { "name": ["Simon", "Marsh", "Gaurav", "Alex", "Selena"], "Maths": [8, 5, 6, 9, 7], "Science": [7, 9, 5, 4, 7], "English": [7, 4, 7, 6, 8], } df = pd.DataFrame(data) a = df.sort_values(by="Science", na_position="first") print(a) #Output : [END]
Selementsect row with maximum and minimum value in Pandas dataframe
https://www.geeksforgeeks.org/select-row-with-maximum-and-minimum-value-in-pandas-dataframe/
# importing pandas and numpy import pandas as pd import numpy as np # data of 2018 drivers world championship dict1 = { "Driver": [ "Hamilton", "Vettel", "Raikkonen", "Verstappen", "Bottas", "Ricciardo", "Hulkenberg", "Perez", "Magnussen", "Sainz", "Alonso", "Ocon", "Leclerc", "Grosjean", "Gasly", "Vandoorne", "Ericsson", "Stroll", "Hartley", "Sirotkin", ], "Points": [ 408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1, ], "Age": [ 33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23, ], } # creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) print(df.head(10))
#Output : 39
Selementsect row with maximum and minimum value in Pandas dataframe # importing pandas and numpy import pandas as pd import numpy as np # data of 2018 drivers world championship dict1 = { "Driver": [ "Hamilton", "Vettel", "Raikkonen", "Verstappen", "Bottas", "Ricciardo", "Hulkenberg", "Perez", "Magnussen", "Sainz", "Alonso", "Ocon", "Leclerc", "Grosjean", "Gasly", "Vandoorne", "Ericsson", "Stroll", "Hartley", "Sirotkin", ], "Points": [ 408, 320, 251, 249, 247, 170, 69, 62, 56, 53, 50, 49, 39, 37, 29, 12, 9, 6, 4, 1, ], "Age": [ 33, 31, 39, 21, 29, 29, 31, 28, 26, 24, 37, 22, 21, 32, 22, 26, 28, 20, 29, 23, ], } # creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) print(df.head(10)) #Output : 39 [END]
Selementsect row with maximum and minimum value in Pandas dataframe
https://www.geeksforgeeks.org/select-row-with-maximum-and-minimum-value-in-pandas-dataframe/
# creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) # the result shows max on # Driver, Points, Age columns. print(df.max())
#Output : 39
Selementsect row with maximum and minimum value in Pandas dataframe # creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) # the result shows max on # Driver, Points, Age columns. print(df.max()) #Output : 39 [END]
Selementsect row with maximum and minimum value in Pandas dataframe
https://www.geeksforgeeks.org/select-row-with-maximum-and-minimum-value-in-pandas-dataframe/
# creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) # Who scored more points ? print(df[df.Points == df.Points.max()])
#Output : 39
Selementsect row with maximum and minimum value in Pandas dataframe # creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) # Who scored more points ? print(df[df.Points == df.Points.max()]) #Output : 39 [END]
Selementsect row with maximum and minimum value in Pandas dataframe
https://www.geeksforgeeks.org/select-row-with-maximum-and-minimum-value-in-pandas-dataframe/
# creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) # what is the maximum age ? print(df.Age.max())
#Output : 39
Selementsect row with maximum and minimum value in Pandas dataframe # creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) # what is the maximum age ? print(df.Age.max()) #Output : 39 [END]
Selementsect row with maximum and minimum value in Pandas dataframe
https://www.geeksforgeeks.org/select-row-with-maximum-and-minimum-value-in-pandas-dataframe/
# creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) # Which row has maximum age | # who is the oldest driver ? print(df[df.Age == df.Age.max()])
#Output : 39
Selementsect row with maximum and minimum value in Pandas dataframe # creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) # Which row has maximum age | # who is the oldest driver ? print(df[df.Age == df.Age.max()]) #Output : 39 [END]
Selementsect row with maximum and minimum value in Pandas dataframe
https://www.geeksforgeeks.org/select-row-with-maximum-and-minimum-value-in-pandas-dataframe/
# creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) # the result shows min on # Driver, Points, Age columns. print(df.min())
#Output : 39
Selementsect row with maximum and minimum value in Pandas dataframe # creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) # the result shows min on # Driver, Points, Age columns. print(df.min()) #Output : 39 [END]
Selementsect row with maximum and minimum value in Pandas dataframe
https://www.geeksforgeeks.org/select-row-with-maximum-and-minimum-value-in-pandas-dataframe/
# creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) # Who scored less points ? print(df[df.Points == df.Points.min()])
#Output : 39
Selementsect row with maximum and minimum value in Pandas dataframe # creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) # Who scored less points ? print(df[df.Points == df.Points.min()]) #Output : 39 [END]
Selementsect row with maximum and minimum value in Pandas dataframe
https://www.geeksforgeeks.org/select-row-with-maximum-and-minimum-value-in-pandas-dataframe/
# creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) # Which row has maximum age | # who is the youngest driver ? print(df[df.Age == df.Age.min()])
#Output : 39
Selementsect row with maximum and minimum value in Pandas dataframe # creating dataframe using DataFrame constructor df = pd.DataFrame(dict1) # Which row has maximum age | # who is the youngest driver ? print(df[df.Age == df.Age.min()]) #Output : 39 [END]
Create a pandas column using for loop
https://www.geeksforgeeks.org/create-a-pandas-column-using-for-loop/
# importing libraries import pandas as pd import numpy as np raw_Data = { "Voter_name": [ "Geek1", "Geek2", "Geek3", "Geek4", "Geek5", "Geek6", "Geek7", "Geek8", ], "Voter_age": [15, 23, 25, 9, 67, 54, 42, np.NaN], } df = pd.DataFrame(raw_Data, columns=["Voter_name", "Voter_age"]) # //DataFrame will look like # # Voter_name Voter_age # Geek1 15 # Geek2 23 # Geek3 25 # Geek4 09 # Geek5 67 # Geek6 54 # Geek7 42 # Geek8 not a number eligible = [] # For each row in the column for age in df["Voter_age"]: if age >= 18: # if Voter eligible eligible.append("Yes") elif age < 18: # if voter is not eligible eligible.append("No") else: eligible.append("Not Sure") # Create a column from the list df["Voter"] = eligible print(df)
#Output :
Create a pandas column using for loop # importing libraries import pandas as pd import numpy as np raw_Data = { "Voter_name": [ "Geek1", "Geek2", "Geek3", "Geek4", "Geek5", "Geek6", "Geek7", "Geek8", ], "Voter_age": [15, 23, 25, 9, 67, 54, 42, np.NaN], } df = pd.DataFrame(raw_Data, columns=["Voter_name", "Voter_age"]) # //DataFrame will look like # # Voter_name Voter_age # Geek1 15 # Geek2 23 # Geek3 25 # Geek4 09 # Geek5 67 # Geek6 54 # Geek7 42 # Geek8 not a number eligible = [] # For each row in the column for age in df["Voter_age"]: if age >= 18: # if Voter eligible eligible.append("Yes") elif age < 18: # if voter is not eligible eligible.append("No") else: eligible.append("Not Sure") # Create a column from the list df["Voter"] = eligible print(df) #Output : [END]
How to rename columns in Pandas DataFrame
https://www.geeksforgeeks.org/how-to-rename-columns-in-pandas-dataframe/
# Import pandas package import pandas as pd # Define a dictionary containing ICC rankings rankings = { "test": ["India", "South Africa", "England", "New Zealand", "Australia"], "odi": ["England", "India", "New Zealand", "South Africa", "Pakistan"], "t20": ["Pakistan", "India", "Australia", "England", "New Zealand"], } # Convert the dictionary into DataFrame rankings_pd = pd.DataFrame(rankings) # Before renaming the columns print(rankings_pd) rankings_pd.rename(columns={"test": "TEST"}, inplace=True) # After renaming the columns print("\nAfter modifying first column:\n", rankings_pd.columns)
#Output : col_test_1 col_odi_1 col_t20_1
How to rename columns in Pandas DataFrame # Import pandas package import pandas as pd # Define a dictionary containing ICC rankings rankings = { "test": ["India", "South Africa", "England", "New Zealand", "Australia"], "odi": ["England", "India", "New Zealand", "South Africa", "Pakistan"], "t20": ["Pakistan", "India", "Australia", "England", "New Zealand"], } # Convert the dictionary into DataFrame rankings_pd = pd.DataFrame(rankings) # Before renaming the columns print(rankings_pd) rankings_pd.rename(columns={"test": "TEST"}, inplace=True) # After renaming the columns print("\nAfter modifying first column:\n", rankings_pd.columns) #Output : col_test_1 col_odi_1 col_t20_1 [END]
How to rename columns in Pandas DataFrame
https://www.geeksforgeeks.org/how-to-rename-columns-in-pandas-dataframe/
# Import pandas package import pandas as pd # Define a dictionary containing ICC rankings rankings = { "test": ["India", "South Africa", "England", "New Zealand", "Australia"], "odi": ["England", "India", "New Zealand", "South Africa", "Pakistan"], "t20": ["Pakistan", "India", "Australia", "England", "New Zealand"], } # Convert the dictionary into DataFrame rankings_pd = pd.DataFrame(rankings) # Before renaming the columns print(rankings_pd.columns) rankings_pd.rename(columns={"test": "TEST", "odi": "ODI", "t20": "T20"}, inplace=True) # After renaming the columns print(rankings_pd.columns)
#Output : col_test_1 col_odi_1 col_t20_1
How to rename columns in Pandas DataFrame # Import pandas package import pandas as pd # Define a dictionary containing ICC rankings rankings = { "test": ["India", "South Africa", "England", "New Zealand", "Australia"], "odi": ["England", "India", "New Zealand", "South Africa", "Pakistan"], "t20": ["Pakistan", "India", "Australia", "England", "New Zealand"], } # Convert the dictionary into DataFrame rankings_pd = pd.DataFrame(rankings) # Before renaming the columns print(rankings_pd.columns) rankings_pd.rename(columns={"test": "TEST", "odi": "ODI", "t20": "T20"}, inplace=True) # After renaming the columns print(rankings_pd.columns) #Output : col_test_1 col_odi_1 col_t20_1 [END]
How to rename columns in Pandas DataFrame
https://www.geeksforgeeks.org/how-to-rename-columns-in-pandas-dataframe/
# Import pandas package import pandas as pd # Define a dictionary containing ICC rankings rankings = { "test": ["India", "South Africa", "England", "New Zealand", "Australia"], "odi": ["England", "India", "New Zealand", "South Africa", "Pakistan"], "t20": ["Pakistan", "India", "Australia", "England", "New Zealand"], } # Convert the dictionary into DataFrame rankings_pd = pd.DataFrame(rankings) # Before renaming the columns print(rankings_pd.columns) rankings_pd.columns = ["TEST", "ODI", "T-20"] # After renaming the columns print(rankings_pd.columns)
#Output : col_test_1 col_odi_1 col_t20_1
How to rename columns in Pandas DataFrame # Import pandas package import pandas as pd # Define a dictionary containing ICC rankings rankings = { "test": ["India", "South Africa", "England", "New Zealand", "Australia"], "odi": ["England", "India", "New Zealand", "South Africa", "Pakistan"], "t20": ["Pakistan", "India", "Australia", "England", "New Zealand"], } # Convert the dictionary into DataFrame rankings_pd = pd.DataFrame(rankings) # Before renaming the columns print(rankings_pd.columns) rankings_pd.columns = ["TEST", "ODI", "T-20"] # After renaming the columns print(rankings_pd.columns) #Output : col_test_1 col_odi_1 col_t20_1 [END]
How to rename columns in Pandas DataFrame
https://www.geeksforgeeks.org/how-to-rename-columns-in-pandas-dataframe/
# Import pandas package import pandas as pd # Define a dictionary containing ICC rankings rankings = { "test": ["India", "South Africa", "England", "New Zealand", "Australia"], "odi": ["England", "India", "New Zealand", "South Africa", "Pakistan"], "t20": ["Pakistan", "India", "Australia", "England", "New Zealand"], } # Convert the dictionary into DataFrame rankings_pd = pd.DataFrame(rankings) # Before renaming the columns print(rankings_pd.columns) rankings_pd.set_axis(["A", "B", "C"], axis="columns", inplace=True) # After renaming the columns print(rankings_pd.columns) rankings_pd.head()
#Output : col_test_1 col_odi_1 col_t20_1
How to rename columns in Pandas DataFrame # Import pandas package import pandas as pd # Define a dictionary containing ICC rankings rankings = { "test": ["India", "South Africa", "England", "New Zealand", "Australia"], "odi": ["England", "India", "New Zealand", "South Africa", "Pakistan"], "t20": ["Pakistan", "India", "Australia", "England", "New Zealand"], } # Convert the dictionary into DataFrame rankings_pd = pd.DataFrame(rankings) # Before renaming the columns print(rankings_pd.columns) rankings_pd.set_axis(["A", "B", "C"], axis="columns", inplace=True) # After renaming the columns print(rankings_pd.columns) rankings_pd.head() #Output : col_test_1 col_odi_1 col_t20_1 [END]
How to rename columns in Pandas DataFrame
https://www.geeksforgeeks.org/how-to-rename-columns-in-pandas-dataframe/
# Import pandas package import pandas as pd # Define a dictionary containing ICC rankings rankings = { "test": ["India", "South Africa", "England", "New Zealand", "Australia"], "odi": ["England", "India", "New Zealand", "South Africa", "Pakistan"], "t20": ["Pakistan", "India", "Australia", "England", "New Zealand"], } # Convert the dictionary into DataFrame rankings_pd = pd.DataFrame(rankings) # Before renaming the columns print(rankings_pd.columns) rankings_pd = rankings_pd.add_prefix("col_") rankings_pd = rankings_pd.add_suffix("_1") # After renaming the columns rankings_pd.head()
#Output : col_test_1 col_odi_1 col_t20_1
How to rename columns in Pandas DataFrame # Import pandas package import pandas as pd # Define a dictionary containing ICC rankings rankings = { "test": ["India", "South Africa", "England", "New Zealand", "Australia"], "odi": ["England", "India", "New Zealand", "South Africa", "Pakistan"], "t20": ["Pakistan", "India", "Australia", "England", "New Zealand"], } # Convert the dictionary into DataFrame rankings_pd = pd.DataFrame(rankings) # Before renaming the columns print(rankings_pd.columns) rankings_pd = rankings_pd.add_prefix("col_") rankings_pd = rankings_pd.add_suffix("_1") # After renaming the columns rankings_pd.head() #Output : col_test_1 col_odi_1 col_t20_1 [END]
How to rename columns in Pandas DataFrame
https://www.geeksforgeeks.org/how-to-rename-columns-in-pandas-dataframe/
# Import pandas package import pandas as pd # Define a dictionary containing ICC rankings rankings = { "test": ["India", "South Africa", "England", "New Zealand", "Australia"], "odi": ["England", "India", "New Zealand", "South Africa", "Pakistan"], "t20": ["Pakistan", "India", "Australia", "England", "New Zealand"], } # Convert the dictionary into DataFrame rankings_pd = pd.DataFrame(rankings) # Before renaming the columns print(rankings_pd.columns) # df = rankings_pd rankings_pd.columns = rankings_pd.columns.str.replace("test", "Col_TEST") rankings_pd.columns = rankings_pd.columns.str.replace("odi", "Col_ODI") rankings_pd.columns = rankings_pd.columns.str.replace("t20", "Col_T20") rankings_pd.head()
#Output : col_test_1 col_odi_1 col_t20_1
How to rename columns in Pandas DataFrame # Import pandas package import pandas as pd # Define a dictionary containing ICC rankings rankings = { "test": ["India", "South Africa", "England", "New Zealand", "Australia"], "odi": ["England", "India", "New Zealand", "South Africa", "Pakistan"], "t20": ["Pakistan", "India", "Australia", "England", "New Zealand"], } # Convert the dictionary into DataFrame rankings_pd = pd.DataFrame(rankings) # Before renaming the columns print(rankings_pd.columns) # df = rankings_pd rankings_pd.columns = rankings_pd.columns.str.replace("test", "Col_TEST") rankings_pd.columns = rankings_pd.columns.str.replace("odi", "Col_ODI") rankings_pd.columns = rankings_pd.columns.str.replace("t20", "Col_T20") rankings_pd.head() #Output : col_test_1 col_odi_1 col_t20_1 [END]
Split a column in Pandas dataframe and get part of it
https://www.geeksforgeeks.org/split-a-column-in-pandas-dataframe-and-get-part-of-it/
import pandas as pd import numpy as np df = pd.DataFrame( { "Geek_ID": ["Geek1_id", "Geek2_id", "Geek3_id", "Geek4_id", "Geek5_id"], "Geek_A": [1, 1, 3, 2, 4], "Geek_B": [1, 2, 3, 4, 6], "Geek_R": np.random.randn(5), } ) # Geek_A Geek_B Geek_ID Geek_R # 0 1 1 Geek1_id random number # 1 1 2 Geek2_id random number # 2 3 3 Geek3_id random number # 3 2 4 Geek4_id random number # 4 4 6 Geek5_id random number print(df.Geek_ID.str.split("_").str[0])
#Output :
Split a column in Pandas dataframe and get part of it import pandas as pd import numpy as np df = pd.DataFrame( { "Geek_ID": ["Geek1_id", "Geek2_id", "Geek3_id", "Geek4_id", "Geek5_id"], "Geek_A": [1, 1, 3, 2, 4], "Geek_B": [1, 2, 3, 4, 6], "Geek_R": np.random.randn(5), } ) # Geek_A Geek_B Geek_ID Geek_R # 0 1 1 Geek1_id random number # 1 1 2 Geek2_id random number # 2 3 3 Geek3_id random number # 3 2 4 Geek4_id random number # 4 4 6 Geek5_id random number print(df.Geek_ID.str.split("_").str[0]) #Output : [END]
Split a column in Pandas dataframe and get part of it
https://www.geeksforgeeks.org/split-a-column-in-pandas-dataframe-and-get-part-of-it/
import pandas as pd import numpy as np df = pd.DataFrame( { "Geek_ID": ["Geek1_id", "Geek2_id", "Geek3_id", "Geek4_id", "Geek5_id"], "Geek_A": [1, 1, 3, 2, 4], "Geek_B": [1, 2, 3, 4, 6], "Geek_R": np.random.randn(5), } ) # Geek_A Geek_B Geek_ID Geek_R # 0 1 1 Geek1_id random number # 1 1 2 Geek2_id random number # 2 3 3 Geek3_id random number # 3 2 4 Geek4_id random number # 4 4 6 Geek5_id random number print(df.Geek_ID.str.split("_").str[0].tolist())
#Output :
Split a column in Pandas dataframe and get part of it import pandas as pd import numpy as np df = pd.DataFrame( { "Geek_ID": ["Geek1_id", "Geek2_id", "Geek3_id", "Geek4_id", "Geek5_id"], "Geek_A": [1, 1, 3, 2, 4], "Geek_B": [1, 2, 3, 4, 6], "Geek_R": np.random.randn(5), } ) # Geek_A Geek_B Geek_ID Geek_R # 0 1 1 Geek1_id random number # 1 1 2 Geek2_id random number # 2 3 3 Geek3_id random number # 3 2 4 Geek4_id random number # 4 4 6 Geek5_id random number print(df.Geek_ID.str.split("_").str[0].tolist()) #Output : [END]
Split a column in Pandas dataframe and get part of it
https://www.geeksforgeeks.org/split-a-column-in-pandas-dataframe-and-get-part-of-it/
import pandas as pd import numpy as np df = pd.DataFrame( { "Geek_ID": ["Geek1_id", "Geek2_id", "Geek3_id", "Geek4_id", "Geek5_id"], "Geek_A": [1, 1, 3, 2, 4], "Geek_B": [1, 2, 3, 4, 6], "Geek_R": np.random.randn(5), } ) # Geek_A Geek_B Geek_ID Geek_R # 0 1 1 Geek1_id random number # 1 1 2 Geek2_id random number # 2 3 3 Geek3_id random number # 3 2 4 Geek4_id random number # 4 4 6 Geek5_id random number print(df.Geek_ID.str.split("_").str[1].tolist())
#Output :
Split a column in Pandas dataframe and get part of it import pandas as pd import numpy as np df = pd.DataFrame( { "Geek_ID": ["Geek1_id", "Geek2_id", "Geek3_id", "Geek4_id", "Geek5_id"], "Geek_A": [1, 1, 3, 2, 4], "Geek_B": [1, 2, 3, 4, 6], "Geek_R": np.random.randn(5), } ) # Geek_A Geek_B Geek_ID Geek_R # 0 1 1 Geek1_id random number # 1 1 2 Geek2_id random number # 2 3 3 Geek3_id random number # 3 2 4 Geek4_id random number # 4 4 6 Geek5_id random number print(df.Geek_ID.str.split("_").str[1].tolist()) #Output : [END]
Getting Unique values from a column in Pandas dataframe
https://www.geeksforgeeks.org/getting-unique-values-from-a-column-in-pandas-dataframe/
# import pandas as pd import pandas as pd gapminder_csv_url = "http://bit.ly/2cLzoxH" # load the data with pd.read_csv record = pd.read_csv(gapminder_csv_url) record.head()
#Output :
Getting Unique values from a column in Pandas dataframe # import pandas as pd import pandas as pd gapminder_csv_url = "http://bit.ly/2cLzoxH" # load the data with pd.read_csv record = pd.read_csv(gapminder_csv_url) record.head() #Output : [END]
Getting Unique values from a column in Pandas dataframe
https://www.geeksforgeeks.org/getting-unique-values-from-a-column-in-pandas-dataframe/
# import pandas as pd import pandas as pd gapminder_csv_url = "http://bit.ly/2cLzoxH" # load the data with pd.read_csv record = pd.read_csv(gapminder_csv_url) print(record["continent"].unique())
#Output :
Getting Unique values from a column in Pandas dataframe # import pandas as pd import pandas as pd gapminder_csv_url = "http://bit.ly/2cLzoxH" # load the data with pd.read_csv record = pd.read_csv(gapminder_csv_url) print(record["continent"].unique()) #Output : [END]
Getting Unique values from a column in Pandas dataframe
https://www.geeksforgeeks.org/getting-unique-values-from-a-column-in-pandas-dataframe/
# import pandas as pd import pandas as pd gapminder_csv_url = "http://bit.ly/2cLzoxH" # load the data with pd.read_csv record = pd.read_csv(gapminder_csv_url) print(record.country.unique())
#Output :
Getting Unique values from a column in Pandas dataframe # import pandas as pd import pandas as pd gapminder_csv_url = "http://bit.ly/2cLzoxH" # load the data with pd.read_csv record = pd.read_csv(gapminder_csv_url) print(record.country.unique()) #Output : [END]
Getting Unique values from a column in Pandas dataframe
https://www.geeksforgeeks.org/getting-unique-values-from-a-column-in-pandas-dataframe/
# Write Python3 code here # import pandas as pd import pandas as pd gapminder_csv_url = "http://bit.ly/2cLzoxH" # load the data with pd.read_csv record = pd.read_csv(gapminder_csv_url) print(pd.unique(record["continent"]))
#Output :
Getting Unique values from a column in Pandas dataframe # Write Python3 code here # import pandas as pd import pandas as pd gapminder_csv_url = "http://bit.ly/2cLzoxH" # load the data with pd.read_csv record = pd.read_csv(gapminder_csv_url) print(pd.unique(record["continent"])) #Output : [END]
Change Data Type for one or more columns in Pandas Dataframe
https://www.geeksforgeeks.org/change-data-type-for-one-or-more-columns-in-pandas-dataframe/
# importing pandas as pd import pandas as pd # sample dataframe df = pd.DataFrame( { "A": [1, 2, 3, 4, 5], "B": ["a", "b", "c", "d", "e"], "C": [1.1, "1.0", "1.3", 2, 5], } ) # converting all columns to string type df = df.astype(str) print(df.dtypes)
#Output : Original_dtypes:
Change Data Type for one or more columns in Pandas Dataframe # importing pandas as pd import pandas as pd # sample dataframe df = pd.DataFrame( { "A": [1, 2, 3, 4, 5], "B": ["a", "b", "c", "d", "e"], "C": [1.1, "1.0", "1.3", 2, 5], } ) # converting all columns to string type df = df.astype(str) print(df.dtypes) #Output : Original_dtypes: [END]
Change Data Type for one or more columns in Pandas Dataframe
https://www.geeksforgeeks.org/change-data-type-for-one-or-more-columns-in-pandas-dataframe/
# importing pandas as pd import pandas as pd # sample dataframe df = pd.DataFrame( { "A": [1, 2, 3, 4, 5], "B": ["a", "b", "c", "d", "e"], "C": [1.1, "1.0", "1.3", 2, 5], } ) # using dictionary to convert specific columns convert_dict = {"A": int, "C": float} df = df.astype(convert_dict) print(df.dtypes)
#Output : Original_dtypes:
Change Data Type for one or more columns in Pandas Dataframe # importing pandas as pd import pandas as pd # sample dataframe df = pd.DataFrame( { "A": [1, 2, 3, 4, 5], "B": ["a", "b", "c", "d", "e"], "C": [1.1, "1.0", "1.3", 2, 5], } ) # using dictionary to convert specific columns convert_dict = {"A": int, "C": float} df = df.astype(convert_dict) print(df.dtypes) #Output : Original_dtypes: [END]
Change Data Type for one or more columns in Pandas Dataframe
https://www.geeksforgeeks.org/change-data-type-for-one-or-more-columns-in-pandas-dataframe/
# importing pandas as pd import pandas as pd # sample dataframe df = pd.DataFrame( { "A": [1, 2, 3, "4", "5"], "B": ["a", "b", "c", "d", "e"], "C": [1.1, "2.1", 3.0, "4.1", "5.1"], } ) # using apply method df[["A", "C"]] = df[["A", "C"]].apply(pd.to_numeric) print(df.dtypes)
#Output : Original_dtypes:
Change Data Type for one or more columns in Pandas Dataframe # importing pandas as pd import pandas as pd # sample dataframe df = pd.DataFrame( { "A": [1, 2, 3, "4", "5"], "B": ["a", "b", "c", "d", "e"], "C": [1.1, "2.1", 3.0, "4.1", "5.1"], } ) # using apply method df[["A", "C"]] = df[["A", "C"]].apply(pd.to_numeric) print(df.dtypes) #Output : Original_dtypes: [END]
Change Data Type for one or more columns in Pandas Dataframe
https://www.geeksforgeeks.org/change-data-type-for-one-or-more-columns-in-pandas-dataframe/
# importing pandas as pd import pandas as pd # sample dataframe df = pd.DataFrame( { "A": [1, 2, 3, 4, 5], "B": ["a", "b", "c", "d", "e"], "C": [1.1, 2.1, 3.0, 4.1, 5.1], }, dtype="object", ) # converting datatypes df = df.infer_objects() print(df.dtypes)
#Output : Original_dtypes:
Change Data Type for one or more columns in Pandas Dataframe # importing pandas as pd import pandas as pd # sample dataframe df = pd.DataFrame( { "A": [1, 2, 3, 4, 5], "B": ["a", "b", "c", "d", "e"], "C": [1.1, 2.1, 3.0, 4.1, 5.1], }, dtype="object", ) # converting datatypes df = df.infer_objects() print(df.dtypes) #Output : Original_dtypes: [END]
Change Data Type for one or more columns in Pandas Dataframe
https://www.geeksforgeeks.org/change-data-type-for-one-or-more-columns-in-pandas-dataframe/
import pandas as pd data = {"name": ["Aman", "Hardik", pd.NA], "qualified": [True, False, pd.NA]} df = pd.DataFrame(data) print("Original_dtypes:") print(df.dtypes) newdf = df.convert_dtypes() print("New_dtypes:") print(newdf.dtypes)
#Output : Original_dtypes:
Change Data Type for one or more columns in Pandas Dataframe import pandas as pd data = {"name": ["Aman", "Hardik", pd.NA], "qualified": [True, False, pd.NA]} df = pd.DataFrame(data) print("Original_dtypes:") print(df.dtypes) newdf = df.convert_dtypes() print("New_dtypes:") print(newdf.dtypes) #Output : Original_dtypes: [END]
Difference of two columns in Pandas dataframe
https://www.geeksforgeeks.org/difference-of-two-columns-in-pandas-dataframe/
import pandas as pd # Create a DataFrame df1 = { "Name": ["George", "Andrea", "micheal", "maggie", "Ravi", "Xien", "Jalpa"], "score1": [62, 47, 55, 74, 32, 77, 86], "score2": [45, 78, 44, 89, 66, 49, 72], } df1 = pd.DataFrame(df1, columns=["Name", "score1", "score2"]) print("Given Dataframe :\n", df1) # getting Difference df1["Score_diff"] = df1["score1"] - df1["score2"] print("\nDifference of score1 and score2 :\n", df1)
#Output :
Difference of two columns in Pandas dataframe import pandas as pd # Create a DataFrame df1 = { "Name": ["George", "Andrea", "micheal", "maggie", "Ravi", "Xien", "Jalpa"], "score1": [62, 47, 55, 74, 32, 77, 86], "score2": [45, 78, 44, 89, 66, 49, 72], } df1 = pd.DataFrame(df1, columns=["Name", "score1", "score2"]) print("Given Dataframe :\n", df1) # getting Difference df1["Score_diff"] = df1["score1"] - df1["score2"] print("\nDifference of score1 and score2 :\n", df1) #Output : [END]
Difference of two columns in Pandas dataframe
https://www.geeksforgeeks.org/difference-of-two-columns-in-pandas-dataframe/
import pandas as pd # Create a DataFrame df1 = { "Name": ["George", "Andrea", "micheal", "maggie", "Ravi", "Xien", "Jalpa"], "score1": [62, 47, 55, 74, 32, 77, 86], "score2": [45, 78, 44, 89, 66, 49, 72], } df1 = pd.DataFrame(df1, columns=["Name", "score1", "score2"]) print("Given Dataframe :\n", df1) df1["Score_diff"] = df1["score1"].sub(df1["score2"], axis=0) print("\nDifference of score1 and score2 :\n", df1)
#Output :
Difference of two columns in Pandas dataframe import pandas as pd # Create a DataFrame df1 = { "Name": ["George", "Andrea", "micheal", "maggie", "Ravi", "Xien", "Jalpa"], "score1": [62, 47, 55, 74, 32, 77, 86], "score2": [45, 78, 44, 89, 66, 49, 72], } df1 = pd.DataFrame(df1, columns=["Name", "score1", "score2"]) print("Given Dataframe :\n", df1) df1["Score_diff"] = df1["score1"].sub(df1["score2"], axis=0) print("\nDifference of score1 and score2 :\n", df1) #Output : [END]
How to drop one or multiple columns in Pandas Dataframe
https://www.geeksforgeeks.org/how-to-drop-one-or-multiple-columns-in-pandas-dataframe/
# Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) df
#Output : A C D E
How to drop one or multiple columns in Pandas Dataframe # Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) df #Output : A C D E [END]
How to drop one or multiple columns in Pandas Dataframe
https://www.geeksforgeeks.org/how-to-drop-one-or-multiple-columns-in-pandas-dataframe/
# Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove column name 'A' df.drop(["A"], axis=1)
#Output : A C D E
How to drop one or multiple columns in Pandas Dataframe # Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove column name 'A' df.drop(["A"], axis=1) #Output : A C D E [END]
How to drop one or multiple columns in Pandas Dataframe
https://www.geeksforgeeks.org/how-to-drop-one-or-multiple-columns-in-pandas-dataframe/
# Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove two columns name is 'C' and 'D' df.drop(["C", "D"], axis=1) # df.drop(columns =['C', 'D'])
#Output : A C D E
How to drop one or multiple columns in Pandas Dataframe # Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove two columns name is 'C' and 'D' df.drop(["C", "D"], axis=1) # df.drop(columns =['C', 'D']) #Output : A C D E [END]
How to drop one or multiple columns in Pandas Dataframe
https://www.geeksforgeeks.org/how-to-drop-one-or-multiple-columns-in-pandas-dataframe/
# Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove three columns as index base df.drop(df.columns[[0, 4, 2]], axis=1, inplace=True) df
#Output : A C D E
How to drop one or multiple columns in Pandas Dataframe # Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove three columns as index base df.drop(df.columns[[0, 4, 2]], axis=1, inplace=True) df #Output : A C D E [END]
How to drop one or multiple columns in Pandas Dataframe
https://www.geeksforgeeks.org/how-to-drop-one-or-multiple-columns-in-pandas-dataframe/
# Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove all columns between column index 1 to 3 df.drop(df.iloc[:, 1:3], inplace=True, axis=1) df
#Output : A C D E
How to drop one or multiple columns in Pandas Dataframe # Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove all columns between column index 1 to 3 df.drop(df.iloc[:, 1:3], inplace=True, axis=1) df #Output : A C D E [END]
How to drop one or multiple columns in Pandas Dataframe
https://www.geeksforgeeks.org/how-to-drop-one-or-multiple-columns-in-pandas-dataframe/
# Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove all columns between column name 'B' to 'D' df.drop(df.ix[:, "B":"D"].columns, axis=1)
#Output : A C D E
How to drop one or multiple columns in Pandas Dataframe # Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove all columns between column name 'B' to 'D' df.drop(df.ix[:, "B":"D"].columns, axis=1) #Output : A C D E [END]
How to drop one or multiple columns in Pandas Dataframe
https://www.geeksforgeeks.org/how-to-drop-one-or-multiple-columns-in-pandas-dataframe/
# Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove all columns between column name 'B' to 'D' df.drop(df.loc[:, "B":"D"].columns, axis=1)
#Output : A C D E
How to drop one or multiple columns in Pandas Dataframe # Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # Remove all columns between column name 'B' to 'D' df.drop(df.loc[:, "B":"D"].columns, axis=1) #Output : A C D E [END]
How to drop one or multiple columns in Pandas Dataframe
https://www.geeksforgeeks.org/how-to-drop-one-or-multiple-columns-in-pandas-dataframe/
# Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) for col in df.columns: if "A" in col: del df[col] df
#Output : A C D E
How to drop one or multiple columns in Pandas Dataframe # Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) for col in df.columns: if "A" in col: del df[col] df #Output : A C D E [END]
How to drop one or multiple columns in Pandas Dataframe
https://www.geeksforgeeks.org/how-to-drop-one-or-multiple-columns-in-pandas-dataframe/
# Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) df.pop("B") df
#Output : A C D E
How to drop one or multiple columns in Pandas Dataframe # Import pandas package import pandas as pd # create a dictionary with five fields each data = { "A": ["A1", "A2", "A3", "A4", "A5"], "B": ["B1", "B2", "B3", "B4", "B5"], "C": ["C1", "C2", "C3", "C4", "C5"], "D": ["D1", "D2", "D3", "D4", "D5"], "E": ["E1", "E2", "E3", "E4", "E5"], } # Convert the dictionary into DataFrame df = pd.DataFrame(data) df.pop("B") df #Output : A C D E [END]
Create a Pandas Series from array
https://www.geeksforgeeks.org/create-a-pandas-series-from-array/
# importing Pandas & numpy import pandas as pd import numpy as np # numpy array data = np.array(["a", "b", "c", "d", "e"]) # creating series s = pd.Series(data) print(s)
#Output :
Create a Pandas Series from array # importing Pandas & numpy import pandas as pd import numpy as np # numpy array data = np.array(["a", "b", "c", "d", "e"]) # creating series s = pd.Series(data) print(s) #Output : [END]
Create a Pandas Series from array
https://www.geeksforgeeks.org/create-a-pandas-series-from-array/
# importing Pandas & numpy import pandas as pd import numpy as np # numpy array data = np.array(["a", "b", "c", "d", "e"]) # creating series s = pd.Series(data, index=[1000, 1001, 1002, 1003, 1004]) print(s)
#Output :
Create a Pandas Series from array # importing Pandas & numpy import pandas as pd import numpy as np # numpy array data = np.array(["a", "b", "c", "d", "e"]) # creating series s = pd.Series(data, index=[1000, 1001, 1002, 1003, 1004]) print(s) #Output : [END]
Creating a Pandas Series from Dictionary
https://www.geeksforgeeks.org/creating-a-pandas-series-from-dictionary/
# import the pandas lib as pd import pandas as pd # create a dictionary dictionary = {"A": 10, "B": 20, "C": 30} # create a series series = pd.Series(dictionary) print(series)
#Output : A 10
Creating a Pandas Series from Dictionary # import the pandas lib as pd import pandas as pd # create a dictionary dictionary = {"A": 10, "B": 20, "C": 30} # create a series series = pd.Series(dictionary) print(series) #Output : A 10 [END]
Creating a Pandas Series from Dictionary
https://www.geeksforgeeks.org/creating-a-pandas-series-from-dictionary/
# import the pandas lib as pd import pandas as pd # create a dictionary dictionary = {"D": 10, "B": 20, "C": 30} # create a series series = pd.Series(dictionary) print(series)
#Output : A 10
Creating a Pandas Series from Dictionary # import the pandas lib as pd import pandas as pd # create a dictionary dictionary = {"D": 10, "B": 20, "C": 30} # create a series series = pd.Series(dictionary) print(series) #Output : A 10 [END]
Creating a Pandas Series from Dictionary
https://www.geeksforgeeks.org/creating-a-pandas-series-from-dictionary/
# import the pandas lib as pd import pandas as pd # create a dictionary dictionary = {"A": 50, "B": 10, "C": 80} # create a series series = pd.Series(dictionary, index=["B", "C", "A"]) print(series)
#Output : A 10
Creating a Pandas Series from Dictionary # import the pandas lib as pd import pandas as pd # create a dictionary dictionary = {"A": 50, "B": 10, "C": 80} # create a series series = pd.Series(dictionary, index=["B", "C", "A"]) print(series) #Output : A 10 [END]
Creating a Pandas Series from Dictionary
https://www.geeksforgeeks.org/creating-a-pandas-series-from-dictionary/
# import the pandas lib as pd import pandas as pd # create a dictionary dictionary = {"A": 50, "B": 10, "C": 80} # create a series series = pd.Series(dictionary, index=["B", "C", "D", "A"]) print(series)
#Output : A 10
Creating a Pandas Series from Dictionary # import the pandas lib as pd import pandas as pd # create a dictionary dictionary = {"A": 50, "B": 10, "C": 80} # create a series series = pd.Series(dictionary, index=["B", "C", "D", "A"]) print(series) #Output : A 10 [END]
Pandas | Basic of Time Series Manipulation
https://www.geeksforgeeks.org/pandas-basic-of-time-series-manipulation/
import pandas as pd from datetime import datetime import numpy as np range_date = pd.date_range(start="1/1/2019", end="1/08/2019", freq="Min") print(range_date)
#Output : DatetimeIndex(['2019-01-01 00:00:00', '2019-01-01 00:01:00',
Pandas | Basic of Time Series Manipulation import pandas as pd from datetime import datetime import numpy as np range_date = pd.date_range(start="1/1/2019", end="1/08/2019", freq="Min") print(range_date) #Output : DatetimeIndex(['2019-01-01 00:00:00', '2019-01-01 00:01:00', [END]
Pandas | Basic of Time Series Manipulation
https://www.geeksforgeeks.org/pandas-basic-of-time-series-manipulation/
import pandas as pd from datetime import datetime import numpy as np range_date = pd.date_range(start="1/1/2019", end="1/08/2019", freq="Min") print(type(range_date[110]))
#Output : DatetimeIndex(['2019-01-01 00:00:00', '2019-01-01 00:01:00',
Pandas | Basic of Time Series Manipulation import pandas as pd from datetime import datetime import numpy as np range_date = pd.date_range(start="1/1/2019", end="1/08/2019", freq="Min") print(type(range_date[110])) #Output : DatetimeIndex(['2019-01-01 00:00:00', '2019-01-01 00:01:00', [END]
Pandas | Basic of Time Series Manipulation
https://www.geeksforgeeks.org/pandas-basic-of-time-series-manipulation/
import pandas as pd from datetime import datetime import numpy as np range_date = pd.date_range(start="1/1/2019", end="1/08/2019", freq="Min") df = pd.DataFrame(range_date, columns=["date"]) df["data"] = np.random.randint(0, 100, size=(len(range_date))) print(df.head(10))
#Output : DatetimeIndex(['2019-01-01 00:00:00', '2019-01-01 00:01:00',
Pandas | Basic of Time Series Manipulation import pandas as pd from datetime import datetime import numpy as np range_date = pd.date_range(start="1/1/2019", end="1/08/2019", freq="Min") df = pd.DataFrame(range_date, columns=["date"]) df["data"] = np.random.randint(0, 100, size=(len(range_date))) print(df.head(10)) #Output : DatetimeIndex(['2019-01-01 00:00:00', '2019-01-01 00:01:00', [END]
Pandas | Basic of Time Series Manipulation
https://www.geeksforgeeks.org/pandas-basic-of-time-series-manipulation/
import pandas as pd from datetime import datetime import numpy as np range_date = pd.date_range(start="1/1/2019", end="1/08/2019", freq="Min") df = pd.DataFrame(range_date, columns=["date"]) df["data"] = np.random.randint(0, 100, size=(len(range_date))) string_data = [str(x) for x in range_date] print(string_data[1:11])
#Output : DatetimeIndex(['2019-01-01 00:00:00', '2019-01-01 00:01:00',
Pandas | Basic of Time Series Manipulation import pandas as pd from datetime import datetime import numpy as np range_date = pd.date_range(start="1/1/2019", end="1/08/2019", freq="Min") df = pd.DataFrame(range_date, columns=["date"]) df["data"] = np.random.randint(0, 100, size=(len(range_date))) string_data = [str(x) for x in range_date] print(string_data[1:11]) #Output : DatetimeIndex(['2019-01-01 00:00:00', '2019-01-01 00:01:00', [END]
Pandas | Basic of Time Series Manipulation
https://www.geeksforgeeks.org/pandas-basic-of-time-series-manipulation/
import pandas as pd from datetime import datetime import numpy as np range_data = pd.date_range(start="1/1/2019", end="1/08/2019", freq="Min") df = pd.DataFrame(range_data, columns=["date"]) df["data"] = np.random.randint(0, 100, size=(len(range_data))) df["datetime"] = pd.to_datetime(df["date"]) df = df.set_index("datetime") df.drop(["date"], axis=1, inplace=True) print(df["2019-01-05"][1:11])
#Output : DatetimeIndex(['2019-01-01 00:00:00', '2019-01-01 00:01:00',
Pandas | Basic of Time Series Manipulation import pandas as pd from datetime import datetime import numpy as np range_data = pd.date_range(start="1/1/2019", end="1/08/2019", freq="Min") df = pd.DataFrame(range_data, columns=["date"]) df["data"] = np.random.randint(0, 100, size=(len(range_data))) df["datetime"] = pd.to_datetime(df["date"]) df = df.set_index("datetime") df.drop(["date"], axis=1, inplace=True) print(df["2019-01-05"][1:11]) #Output : DatetimeIndex(['2019-01-01 00:00:00', '2019-01-01 00:01:00', [END]
Read More
https://www.geeksforgeeks.org/how-to-get-the-daily-news-using-python/
import requests from bs4 import BeautifulSoup
#Output : pip install bs4
Read More import requests from bs4 import BeautifulSoup #Output : pip install bs4 [END]
Read More
https://www.geeksforgeeks.org/how-to-get-the-daily-news-using-python/
url = "https://www.bbc.com/news" response = requests.get(url)
#Output : pip install bs4
Read More url = "https://www.bbc.com/news" response = requests.get(url) #Output : pip install bs4 [END]
Read More
https://www.geeksforgeeks.org/how-to-get-the-daily-news-using-python/
soup = BeautifulSoup(response.text, "html.parser") headlines = soup.find("body").find_all("h3") for x in headlines: print(x.text.strip())
#Output : pip install bs4
Read More soup = BeautifulSoup(response.text, "html.parser") headlines = soup.find("body").find_all("h3") for x in headlines: print(x.text.strip()) #Output : pip install bs4 [END]
Read More
https://www.geeksforgeeks.org/how-to-get-the-daily-news-using-python/
import requests from bs4 import BeautifulSoup url = "https://www.bbc.com/news" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") headlines = soup.find("body").find_all("h3") for x in headlines: print(x.text.strip())
#Output : pip install bs4
Read More import requests from bs4 import BeautifulSoup url = "https://www.bbc.com/news" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") headlines = soup.find("body").find_all("h3") for x in headlines: print(x.text.strip()) #Output : pip install bs4 [END]
Read More
https://www.geeksforgeeks.org/how-to-get-the-daily-news-using-python/
import requests from bs4 import BeautifulSoup url = "https://www.bbc.com/news" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") headlines = soup.find("body").find_all("h3") unwanted = [ "BBC World News TV", "BBC World Service Radio", "News daily newsletter", "Mobile app", "Get in touch", ] for x in list(dict.fromkeys(headlines)): if x.text.strip() not in unwanted: print(x.text.strip())
#Output : pip install bs4
Read More import requests from bs4 import BeautifulSoup url = "https://www.bbc.com/news" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") headlines = soup.find("body").find_all("h3") unwanted = [ "BBC World News TV", "BBC World Service Radio", "News daily newsletter", "Mobile app", "Get in touch", ] for x in list(dict.fromkeys(headlines)): if x.text.strip() not in unwanted: print(x.text.strip()) #Output : pip install bs4 [END]
Word guessing game in Python
https://www.geeksforgeeks.org/python-program-for-word-guessing-game/
import random # library that we use in order to choose # on random words from a list of words name = input("What is your name? ") # Here the user is asked to enter the name first print("Good Luck ! ", name) words = [ "rainbow", "computer", "science", "programming", "python", "mathematics", "player", "condition", "reverse", "water", "board", "geeks", ] # Function will choose one random # word from this list of words word = random.choice(words) print("Guess the characters") guesses = "" # any number of turns can be used here turns = 12 while turns > 0: # counts the number of times a user fails failed = 0 # all characters from the input # word taking one at a time. for char in word: # comparing that character with # the character in guesses if char in guesses: print(char, end=" ") else: print("_") # for every failure 1 will be # incremented in failure failed += 1 if failed == 0: # user will win the game if failure is 0 # and 'You Win' will be given as output print("You Win") # this print the correct word print("The word is: ", word) break # if user has input the wrong alphabet then # it will ask user to enter another alphabet print() guess = input("guess a character:") # every input character will be stored in guesses guesses += guess # check input with the character in word if guess not in word: turns -= 1 # if the character doesn?????????t match the word # then ?????????Wrong????????? will be given as out"Wrong") # this will print the number of # turns left for the user print("You have", +turns, "more guesses") if turns == 0: print("You Loose")
#Output : What is your name? Gautam
Word guessing game in Python import random # library that we use in order to choose # on random words from a list of words name = input("What is your name? ") # Here the user is asked to enter the name first print("Good Luck ! ", name) words = [ "rainbow", "computer", "science", "programming", "python", "mathematics", "player", "condition", "reverse", "water", "board", "geeks", ] # Function will choose one random # word from this list of words word = random.choice(words) print("Guess the characters") guesses = "" # any number of turns can be used here turns = 12 while turns > 0: # counts the number of times a user fails failed = 0 # all characters from the input # word taking one at a time. for char in word: # comparing that character with # the character in guesses if char in guesses: print(char, end=" ") else: print("_") # for every failure 1 will be # incremented in failure failed += 1 if failed == 0: # user will win the game if failure is 0 # and 'You Win' will be given as output print("You Win") # this print the correct word print("The word is: ", word) break # if user has input the wrong alphabet then # it will ask user to enter another alphabet print() guess = input("guess a character:") # every input character will be stored in guesses guesses += guess # check input with the character in word if guess not in word: turns -= 1 # if the character doesn?????????t match the word # then ?????????Wrong????????? will be given as out"Wrong") # this will print the number of # turns left for the user print("You have", +turns, "more guesses") if turns == 0: print("You Loose") #Output : What is your name? Gautam [END]
Word guessing game in Python
https://www.geeksforgeeks.org/python-program-for-word-guessing-game/
import random def isword(user_word,wordly_word): for x in user_word: print(x,end=" ") print() #If alphabet present in same position green #if alphabet present in word yellow #if alphabet is not present black for i in range(len(user_word)): if user_word[i] == wordly_word[i]: print("????",end ="") elif user_word[i] in wordly_word: print("????",end="") else: print("",end="") #if word present return true else return false if user_word == wordly_word: return 1 else: return 0 import random random_word = random.choice(words) print(random_word) print("Let's Play Wordle") message,i = {0:"Marvellous",1:"Excellent",2:"Very good",3:"Nice",4:"Good",5:"Ok"},6 while i>0: user_word=input("\nEnter word: ") if (len(user_word)==5 and user_word.isalpha()): i = i-1 if isword(user_word,random_word): print("\n",message[i]) break else: continue else: print("Please enter a valid word") else: print("End of Game, the correct word is:",random_word)
From code
Word guessing game in Python import random def isword(user_word,wordly_word): for x in user_word: print(x,end=" ") print() #If alphabet present in same position green #if alphabet present in word yellow #if alphabet is not present black for i in range(len(user_word)): if user_word[i] == wordly_word[i]: print("????",end ="") elif user_word[i] in wordly_word: print("????",end="") else: print("",end="") #if word present return true else return false if user_word == wordly_word: return 1 else: return 0 import random random_word = random.choice(words) print(random_word) print("Let's Play Wordle") message,i = {0:"Marvellous",1:"Excellent",2:"Very good",3:"Nice",4:"Good",5:"Ok"},6 while i>0: user_word=input("\nEnter word: ") if (len(user_word)==5 and user_word.isalpha()): i = i-1 if isword(user_word,random_word): print("\n",message[i]) break else: continue else: print("Please enter a valid word") else: print("End of Game, the correct word is:",random_word) From code [END]
Hangman Game in Python
https://www.geeksforgeeks.org/hangman-game-python/
# Python Program to illustrate# Hangman Gameimport randomfrom collections import Counter??????someWords = '''apple banana mango strawberryorange grape pineapple apricot lemon coconut watermeloncherry papaya berry peach lychee muskmelon'''??????someWords = someWords.split(' ')# randomly choose a secret word f"someWords" LIST.word = random.choice(someWords)??????if __name__ == '__main__':????????????????????????print('Guess the word! HINT: word is a name of a fruit')??????????????????????????????for i in word:??????????????????????????????????????????????????????# For printing the empty spaces for letters of the word????????????????????????????????????????????????print('_', end=' ')????????????????????????print()??????????????????????????????playing = True????????????????????????# list for storing the letters guessed by the player????????????????????????letterGuessed = ''????????????????????????chances = len(word) + 2????????????????????????correct = 0????????????????????????flag = 0????????????????????????try:????????????????????????????????????????????????while (chances != 0) and flag == 0:?????? # flag is updated when the word is correctly guessed????????????????????????????????????????????????????????????????????????print()????????????????????????????????????????????????????????????????????????chances -= 1???????????????y a LETTER')????????????????????????????????????????????????????????????????????????????????????????????????continue????????????????????????????????????????????????????????????????????????else if len(guess) & gt????????????????????????????????????????????????????????????????????????1:????????????????????????????????????????????????????????????????????????????????????????????????print('Enter only a SINGLE letter')????????????????????????????????????????????????????????????????????????????????????????????????continue????????????????????????????????????????????????????????????????????????else if guess in letterGuessed:????????????????????????????????????????????????????????????????????????????????????????????????print('You have already guessed that letter')????????????????????????????????????????????????????????????????????????????????????????????????continue??????????????????????????????????????????????????????????????????????????????# If letter is guessed correctly?????????????????????????????????????????????????????????????????????????print(char, end=' ')????????????????????????????????????????correct += 1????????????????????????????????# If user has guessed all the letters????????????????????????????????# Once the correct word is guessed fully,????????????????????????????????else if (Counter(letterGuessed) == Counter(word)):????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????# the game ends, even if chances remain????????????????????????????????????????print(& quot??????????????????????????????????????????????????????The word is: & quot??????????????????????????????????????????????????????, end=' ')????????????????????????????????????????print(word)????????????????????????????????????????flag = 1????????????????????????????????????????print('Congratulations, You won!')????????????????????????????????????????break?? # To break out of the for loop????????????????????????????????????????break?? # To break out of the while loop????????????????????????????????else:????????????????????????????????????????print('_', end=' ')??????????????????# If user has used all of his chances????????????????if chances & lt????????????????= 0 and (Counter(letterGuessed) != Counter(word)):????????????????????????print()????????????????????????print('You lost! Try again..')????????????????????????print('The word was {}'.format(word))??????????except KeyboardInterrupt:????????????????print()????????????????print('Bye! Try again.')????????????????exit()
#Output : omkarpathak@omkarpathak-Inspiron-3542:~/Documents/
Hangman Game in Python # Python Program to illustrate# Hangman Gameimport randomfrom collections import Counter??????someWords = '''apple banana mango strawberryorange grape pineapple apricot lemon coconut watermeloncherry papaya berry peach lychee muskmelon'''??????someWords = someWords.split(' ')# randomly choose a secret word f"someWords" LIST.word = random.choice(someWords)??????if __name__ == '__main__':????????????????????????print('Guess the word! HINT: word is a name of a fruit')??????????????????????????????for i in word:??????????????????????????????????????????????????????# For printing the empty spaces for letters of the word????????????????????????????????????????????????print('_', end=' ')????????????????????????print()??????????????????????????????playing = True????????????????????????# list for storing the letters guessed by the player????????????????????????letterGuessed = ''????????????????????????chances = len(word) + 2????????????????????????correct = 0????????????????????????flag = 0????????????????????????try:????????????????????????????????????????????????while (chances != 0) and flag == 0:?????? # flag is updated when the word is correctly guessed????????????????????????????????????????????????????????????????????????print()????????????????????????????????????????????????????????????????????????chances -= 1???????????????y a LETTER')????????????????????????????????????????????????????????????????????????????????????????????????continue????????????????????????????????????????????????????????????????????????else if len(guess) & gt????????????????????????????????????????????????????????????????????????1:????????????????????????????????????????????????????????????????????????????????????????????????print('Enter only a SINGLE letter')????????????????????????????????????????????????????????????????????????????????????????????????continue????????????????????????????????????????????????????????????????????????else if guess in letterGuessed:????????????????????????????????????????????????????????????????????????????????????????????????print('You have already guessed that letter')????????????????????????????????????????????????????????????????????????????????????????????????continue??????????????????????????????????????????????????????????????????????????????# If letter is guessed correctly?????????????????????????????????????????????????????????????????????????print(char, end=' ')????????????????????????????????????????correct += 1????????????????????????????????# If user has guessed all the letters????????????????????????????????# Once the correct word is guessed fully,????????????????????????????????else if (Counter(letterGuessed) == Counter(word)):????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????# the game ends, even if chances remain????????????????????????????????????????print(& quot??????????????????????????????????????????????????????The word is: & quot??????????????????????????????????????????????????????, end=' ')????????????????????????????????????????print(word)????????????????????????????????????????flag = 1????????????????????????????????????????print('Congratulations, You won!')????????????????????????????????????????break?? # To break out of the for loop????????????????????????????????????????break?? # To break out of the while loop????????????????????????????????else:????????????????????????????????????????print('_', end=' ')??????????????????# If user has used all of his chances????????????????if chances & lt????????????????= 0 and (Counter(letterGuessed) != Counter(word)):????????????????????????print()????????????????????????print('You lost! Try again..')????????????????????????print('The word was {}'.format(word))??????????except KeyboardInterrupt:????????????????print()????????????????print('Bye! Try again.')????????????????exit() #Output : omkarpathak@omkarpathak-Inspiron-3542:~/Documents/ [END]
21 Number game in Python
https://www.geeksforgeeks.org/21-number-game-in-python/
# Python code to play 21 Number game # returns the nearest multiple to 4 def nearestMultiple(num): if num >= 4: near = num + (4 - (num % 4)) else: near = 4 return near def lose1(): print("\n\nYOU LOSE !") print("Better luck next time !") exit(0) # checks whether the numbers are consecutive def check(xyz): i = 1 while i < len(xyz): if (xyz[i] - xyz[i - 1]) != 1: return False i = i + 1 return True # starts the game def start1(): xyz = [] last = 0 while True: print("Enter 'F' to take the first chance.") print("Enter 'S' to take the second chance.") chance = input("> ") # player takes the first chance if chance == "F": while True: if last == 20: lose1() else: print("\nYour Turn.") print("\nHow many numbers do you wish to enter?") inp = int(input("> ")) if inp > 0 and inp <= 3: comp = 4 - inp else: print("Wrong input. You are disqualified from the game.") lose1() i, j = 1, 1 print("Now enter the values") while i <= inp: a = input("> ") a = int(a) xyz.append(a) i = i + 1 # store the last element of xyz. last = xyz[-1] # checks whether the input # numbers are consecutive if check(xyz) == True: if last == 21: lose1() else: # "Computer's turn." while j <= comp: xyz.append(last + j) j = j + 1 print("Order of inputs after computer's turn is: ") print(xyz) last = xyz[-1] else: print("\nYou did not input consecutive integers.") lose1() # player takes the second chance elif chance == "S": comp = 1 last = 0 while last < 20: # "Computer's turn" j = 1 while j <= comp: xyz.append(last + j) j = j + 1 print("Order of inputs after computer's turn is:") print(xyz) if xyz[-1] == 20: lose1() else: print("\nYour turn.") print("\nHow many numbers do you wish to enter?") inp = input("> ") inp = int(inp) i = 1 print("Enter your values") while i <= inp: xyz.append(int(input("> "))) i = i + 1 last = xyz[-1] if check(xyz) == True: # print (xyz) near = nearestMultiple(last) comp = near - last if comp == 4: comp = 3 else: comp = comp else: # if inputs are not consecutive # automatically disqualified print("\nYou did not input consecutive integers.") # print ("You are disqualified from the game.") lose1() print("\n\nCONGRATULATIONS !!!") print("YOU WON !") exit(0) else: print("wrong choice") game = True while game == True: print("Player 2 is Computer.") print("Do you want to play the 21 number game? (Yes / No)") ans = input("> ") if ans == "Yes": start1() else: print("Do you want quit the game?(yes / no)") nex = input("> ") if nex == "yes": print("You are quitting the game...") exit(0) elif nex == "no": print("Continuing...") else: print("Wrong choice")
#Output : Player 2 is Computer.
21 Number game in Python # Python code to play 21 Number game # returns the nearest multiple to 4 def nearestMultiple(num): if num >= 4: near = num + (4 - (num % 4)) else: near = 4 return near def lose1(): print("\n\nYOU LOSE !") print("Better luck next time !") exit(0) # checks whether the numbers are consecutive def check(xyz): i = 1 while i < len(xyz): if (xyz[i] - xyz[i - 1]) != 1: return False i = i + 1 return True # starts the game def start1(): xyz = [] last = 0 while True: print("Enter 'F' to take the first chance.") print("Enter 'S' to take the second chance.") chance = input("> ") # player takes the first chance if chance == "F": while True: if last == 20: lose1() else: print("\nYour Turn.") print("\nHow many numbers do you wish to enter?") inp = int(input("> ")) if inp > 0 and inp <= 3: comp = 4 - inp else: print("Wrong input. You are disqualified from the game.") lose1() i, j = 1, 1 print("Now enter the values") while i <= inp: a = input("> ") a = int(a) xyz.append(a) i = i + 1 # store the last element of xyz. last = xyz[-1] # checks whether the input # numbers are consecutive if check(xyz) == True: if last == 21: lose1() else: # "Computer's turn." while j <= comp: xyz.append(last + j) j = j + 1 print("Order of inputs after computer's turn is: ") print(xyz) last = xyz[-1] else: print("\nYou did not input consecutive integers.") lose1() # player takes the second chance elif chance == "S": comp = 1 last = 0 while last < 20: # "Computer's turn" j = 1 while j <= comp: xyz.append(last + j) j = j + 1 print("Order of inputs after computer's turn is:") print(xyz) if xyz[-1] == 20: lose1() else: print("\nYour turn.") print("\nHow many numbers do you wish to enter?") inp = input("> ") inp = int(inp) i = 1 print("Enter your values") while i <= inp: xyz.append(int(input("> "))) i = i + 1 last = xyz[-1] if check(xyz) == True: # print (xyz) near = nearestMultiple(last) comp = near - last if comp == 4: comp = 3 else: comp = comp else: # if inputs are not consecutive # automatically disqualified print("\nYou did not input consecutive integers.") # print ("You are disqualified from the game.") lose1() print("\n\nCONGRATULATIONS !!!") print("YOU WON !") exit(0) else: print("wrong choice") game = True while game == True: print("Player 2 is Computer.") print("Do you want to play the 21 number game? (Yes / No)") ans = input("> ") if ans == "Yes": start1() else: print("Do you want quit the game?(yes / no)") nex = input("> ") if nex == "yes": print("You are quitting the game...") exit(0) elif nex == "no": print("Continuing...") else: print("Wrong choice") #Output : Player 2 is Computer. [END]
Mastermind Game using Python
https://www.geeksforgeeks.org/mastermind-game-using-python/
import random????????????# the .randrange() function generates a# random number within the specified range.num = random.randrange(1000, 10000)??????n "Guess the 4 digit number:"))??????# condition to test equality of the# guess made. Program terminates if true.if (n == num):??????????"Great! You guessed the number in just 1 try! You're a Mastermind!")else:????????????????????????# ctr variable initialized. It will keep count of????????????????????????# the number of tries the Player takes to guess the number.????????????????????????ctr = 0??????????????????????????????# while loop repeats as long as the????????????????????????# Player fails to guess the number correctly.????????????????????????while (n != num):????????????????????????????????????????????????# variable increments every time the loop????????????????????????????????????????????????# is executed, giving an idea of how many????????????????????????????????????????????????# guesses were made.????????????????????????????????????????????????ctr += 1??????????????????????????????????????????????????????count = 0??????????????????????????????????????????????????????# explicit type conversion of an integer to????????????????????????????????????????????????# a string in order to ease extraction of digits????????????????????????????????????????????????n = str(n)????????????????????????????????????????um[i]):????????????????????????????????????????????????????????????????????????????????????????????????# number of digits guessed correctly increments????????????????????????????????????????????????????????????????????????????????????????????????count += 1????????????????????????????????????????????????????????????????????????????????????????????????# hence, the digit is stored in correct[].????????????????????????????????????????????????????????????????????????????????????????????????correct[i] = n[i]?????????????????????????????????????????????????"Not quite the number. But you did get ",???????????????????????????????????????????" digit(s) correct!")????????????????????????????????????????????????????????????# second code is not supposed to print the guessed numbers, from the sample output, here I get we are not recording the position of the guess,but count. But as per the explanation, the code should not print the guessed numbers, rather give thei"Also these numbers in your input were correct.")????????????????????????????????????????????????????????????????????????# for k in correct:????????????????????????????????????????????????????????????????????????#?????????????????? print"Enter your next choice of numbers: "))??????????????????????????????????????????????????????# when none of the digits are guessed correctly.????????????????????????????"None of the numbers in your input match.")??????????????????????????????????????"Enter your next choice of numbers: "))??????????????????????????????# condition for equality.????????????????????????if n == num:????????????????????????# ctr must be incremented when the n==num gets executed as we have the other incrmentation in the n!=num condi"You've become a Mastermind!")??????????????????????"It took you only", ctr, "tries.")
#Output : Player 1, set the number: 5672
Mastermind Game using Python import random????????????# the .randrange() function generates a# random number within the specified range.num = random.randrange(1000, 10000)??????n "Guess the 4 digit number:"))??????# condition to test equality of the# guess made. Program terminates if true.if (n == num):??????????"Great! You guessed the number in just 1 try! You're a Mastermind!")else:????????????????????????# ctr variable initialized. It will keep count of????????????????????????# the number of tries the Player takes to guess the number.????????????????????????ctr = 0??????????????????????????????# while loop repeats as long as the????????????????????????# Player fails to guess the number correctly.????????????????????????while (n != num):????????????????????????????????????????????????# variable increments every time the loop????????????????????????????????????????????????# is executed, giving an idea of how many????????????????????????????????????????????????# guesses were made.????????????????????????????????????????????????ctr += 1??????????????????????????????????????????????????????count = 0??????????????????????????????????????????????????????# explicit type conversion of an integer to????????????????????????????????????????????????# a string in order to ease extraction of digits????????????????????????????????????????????????n = str(n)????????????????????????????????????????um[i]):????????????????????????????????????????????????????????????????????????????????????????????????# number of digits guessed correctly increments????????????????????????????????????????????????????????????????????????????????????????????????count += 1????????????????????????????????????????????????????????????????????????????????????????????????# hence, the digit is stored in correct[].????????????????????????????????????????????????????????????????????????????????????????????????correct[i] = n[i]?????????????????????????????????????????????????"Not quite the number. But you did get ",???????????????????????????????????????????" digit(s) correct!")????????????????????????????????????????????????????????????# second code is not supposed to print the guessed numbers, from the sample output, here I get we are not recording the position of the guess,but count. But as per the explanation, the code should not print the guessed numbers, rather give thei"Also these numbers in your input were correct.")????????????????????????????????????????????????????????????????????????# for k in correct:????????????????????????????????????????????????????????????????????????#?????????????????? print"Enter your next choice of numbers: "))??????????????????????????????????????????????????????# when none of the digits are guessed correctly.????????????????????????????"None of the numbers in your input match.")??????????????????????????????????????"Enter your next choice of numbers: "))??????????????????????????????# condition for equality.????????????????????????if n == num:????????????????????????# ctr must be incremented when the n==num gets executed as we have the other incrmentation in the n!=num condi"You've become a Mastermind!")??????????????????????"It took you only", ctr, "tries.") #Output : Player 1, set the number: 5672 [END]
Mastermind Game using Python
https://www.geeksforgeeks.org/mastermind-game-using-python/
import random # the .randrange() function generates # a random number within the specified range. num = random.randrange(1000, 10000) n = int(input("Guess the 4 digit number:")) # condition to test equality of the # guess made. Program terminates if true. if n == num: print("Great! You guessed the number in just 1 try! You're a Mastermind!") else: # ctr variable initialized. It will keep count of # the number of tries the Player takes to guess the number. ctr = 0 # while loop repeats as long as the Player # fails to guess the number correctly. while n != num: # variable increments every time the loop # is executed, giving an idea of how many # guesses were made. ctr += 1 count = 0 # explicit type conversion of an integer to # a string in order to ease extraction of digits n = str(n) # explicit type conversion of a string to an integer num = str(num) # correct[] list stores digits which are correct correct = [] # for loop runs 4 times since the number has 4 digits. for i in range(0, 4): # checking for equality of digits if n[i] == num[i]: # number of digits guessed correctly increments count += 1 # hence, the digit is stored in correct[]. correct.append(n[i]) else: continue # when not all the digits are guessed correctly. if (count < 4) and (count != 0): print("Not quite the number. But you did get ", count, " digit(s) correct!") print("Also these numbers in your input were correct.") for k in correct: print(k, end=" ") print("\n") print("\n") n = int(input("Enter your next choice of numbers: ")) # when none of the digits are guessed correctly. elif count == 0: print("None of the numbers in your input match.") n = int(input("Enter your next choice of numbers: ")) if n == num: print("You've become a Mastermind!") print("It took you only", ctr, "tries.")
#Output : Player 1, set the number: 5672
Mastermind Game using Python import random # the .randrange() function generates # a random number within the specified range. num = random.randrange(1000, 10000) n = int(input("Guess the 4 digit number:")) # condition to test equality of the # guess made. Program terminates if true. if n == num: print("Great! You guessed the number in just 1 try! You're a Mastermind!") else: # ctr variable initialized. It will keep count of # the number of tries the Player takes to guess the number. ctr = 0 # while loop repeats as long as the Player # fails to guess the number correctly. while n != num: # variable increments every time the loop # is executed, giving an idea of how many # guesses were made. ctr += 1 count = 0 # explicit type conversion of an integer to # a string in order to ease extraction of digits n = str(n) # explicit type conversion of a string to an integer num = str(num) # correct[] list stores digits which are correct correct = [] # for loop runs 4 times since the number has 4 digits. for i in range(0, 4): # checking for equality of digits if n[i] == num[i]: # number of digits guessed correctly increments count += 1 # hence, the digit is stored in correct[]. correct.append(n[i]) else: continue # when not all the digits are guessed correctly. if (count < 4) and (count != 0): print("Not quite the number. But you did get ", count, " digit(s) correct!") print("Also these numbers in your input were correct.") for k in correct: print(k, end=" ") print("\n") print("\n") n = int(input("Enter your next choice of numbers: ")) # when none of the digits are guessed correctly. elif count == 0: print("None of the numbers in your input match.") n = int(input("Enter your next choice of numbers: ")) if n == num: print("You've become a Mastermind!") print("It took you only", ctr, "tries.") #Output : Player 1, set the number: 5672 [END]
2048 Game in Python
https://www.geeksforgeeks.org/2048-game-in-python/
# logic.py to be # imported in the 2048.py file # importing random package # for methods to generate random # numbers. import random # function to initialize game / grid # at the start def start_game(): # declaring an empty list then # appending 4 list each with four # elements as 0. mat = [] for i in range(4): mat.append([0] * 4) # printing controls for user print("Commands are as follows : ") print("'W' or 'w' : Move Up") print("'S' or 's' : Move Down") print("'A' or 'a' : Move Left") print("'D' or 'd' : Move Right") # calling the function to add # a new 2 in grid after every step add_new_2(mat) return mat # function to add a new 2 in # grid at any random empty cell def add_new_2(mat): # choosing a random index for # row and column. r = random.randint(0, 3) c = random.randint(0, 3) # while loop will break as the # random cell chosen will be empty # (or contains zero) while mat[r] != 0: r = random.randint(0, 3) c = random.randint(0, 3) # we will place a 2 at that empty # random cell. mat[r] = 2 # function to get the current # state of game def get_current_state(mat): # if any cell contains # 2048 we have won for i in range(4): for j in range(4): if mat[i][j] == 2048: return "WON" # if we are still left with # atleast one empty cell # game is not yet over for i in range(4): for j in range(4): if mat[i][j] == 0: return "GAME NOT OVER" # or if no cell is empty now # but if after any move left, right, # up or down, if any two cells # gets merged and create an empty # cell then also game is not yet over for i in range(3): for j in range(3): if mat[i][j] == mat[i + 1][j] or mat[i][j] == mat[i][j + 1]: return "GAME NOT OVER" for j in range(3): if mat[3][j] == mat[3][j + 1]: return "GAME NOT OVER" for i in range(3): if mat[i][3] == mat[i + 1][3]: return "GAME NOT OVER" # else we have lost the game return "LOST" # all the functions defined below # are for left swap initially. # function to compress the grid # after every step before and # after merging cells. def compress(mat): # bool variable to determine # any change happened or not changed = False # empty grid new_mat = [] # with all cells empty for i in range(4): new_mat.append([0] * 4) # here we will shift entries # of each cell to it's extreme # left row by row # loop to traverse rows for i in range(4): pos = 0 # loop to traverse each column # in respective row for j in range(4): if mat[i][j] != 0: # if cell is non empty then # we will shift it's number to # previous empty cell in that row # denoted by pos variable new_mat[i][pos] = mat[i][j] if j != pos: changed = True pos += 1 # returning new compressed matrix # and the flag variable. return new_mat, changed # function to merge the cells # in matrix after compressing def merge(mat): changed = False for i in range(4): for j in range(3): # if current cell has same value as # next cell in the row and they # are non empty then if mat[i][j] == mat[i][j + 1] and mat[i][j] != 0: # double current cell value and # empty the next cell mat[i][j] = mat[i][j] * 2 mat[i][j + 1] = 0 # make bool variable True indicating # the new grid after merging is # different. changed = True return mat, changed # function to reverse the matrix # means reversing the content of # each row (reversing the sequence) def reverse(mat): new_mat = [] for i in range(4): new_mat.append([]) for j in range(4): new_mat[i].append(mat[i][3 - j]) return new_mat # function to get the transpose # of matrix means interchanging # rows and column def transpose(mat): new_mat = [] for i in range(4): new_mat.append([]) for j in range(4): new_mat[i].append(mat[j][i]) return new_mat # function to update the matrix # if we move / swipe left def move_left(grid): # first compress the grid new_grid, changed1 = compress(grid) # then merge the cells. new_grid, changed2 = merge(new_grid) changed = changed1 or changed2 # again compress after merging. new_grid, temp = compress(new_grid) # return new matrix and bool changed # telling whether the grid is same # or different return new_grid, changed # function to update the matrix # if we move / swipe right def move_right(grid): # to move right we just reverse # the matrix new_grid = reverse(grid) # then move left new_grid, changed = move_left(new_grid) # then again reverse matrix will # give us desired result new_grid = reverse(new_grid) return new_grid, changed # function to update the matrix # if we move / swipe up def move_up(grid): # to move up we just take # transpose of matrix new_grid = transpose(grid) # then move left (calling all # included functions) then new_grid, changed = move_left(new_grid) # again take transpose will give # desired results new_grid = transpose(new_grid) return new_grid, changed # function to update the matrix # if we move / swipe down def move_down(grid): # to move down we take transpose new_grid = transpose(grid) # move right and then again new_grid, changed = move_right(new_grid) # take transpose will give desired # results. new_grid = transpose(new_grid) return new_grid, changed # this file only contains all the logic # functions to be called in main function # present in the other file
#Output : Commands are as follows :
2048 Game in Python # logic.py to be # imported in the 2048.py file # importing random package # for methods to generate random # numbers. import random # function to initialize game / grid # at the start def start_game(): # declaring an empty list then # appending 4 list each with four # elements as 0. mat = [] for i in range(4): mat.append([0] * 4) # printing controls for user print("Commands are as follows : ") print("'W' or 'w' : Move Up") print("'S' or 's' : Move Down") print("'A' or 'a' : Move Left") print("'D' or 'd' : Move Right") # calling the function to add # a new 2 in grid after every step add_new_2(mat) return mat # function to add a new 2 in # grid at any random empty cell def add_new_2(mat): # choosing a random index for # row and column. r = random.randint(0, 3) c = random.randint(0, 3) # while loop will break as the # random cell chosen will be empty # (or contains zero) while mat[r] != 0: r = random.randint(0, 3) c = random.randint(0, 3) # we will place a 2 at that empty # random cell. mat[r] = 2 # function to get the current # state of game def get_current_state(mat): # if any cell contains # 2048 we have won for i in range(4): for j in range(4): if mat[i][j] == 2048: return "WON" # if we are still left with # atleast one empty cell # game is not yet over for i in range(4): for j in range(4): if mat[i][j] == 0: return "GAME NOT OVER" # or if no cell is empty now # but if after any move left, right, # up or down, if any two cells # gets merged and create an empty # cell then also game is not yet over for i in range(3): for j in range(3): if mat[i][j] == mat[i + 1][j] or mat[i][j] == mat[i][j + 1]: return "GAME NOT OVER" for j in range(3): if mat[3][j] == mat[3][j + 1]: return "GAME NOT OVER" for i in range(3): if mat[i][3] == mat[i + 1][3]: return "GAME NOT OVER" # else we have lost the game return "LOST" # all the functions defined below # are for left swap initially. # function to compress the grid # after every step before and # after merging cells. def compress(mat): # bool variable to determine # any change happened or not changed = False # empty grid new_mat = [] # with all cells empty for i in range(4): new_mat.append([0] * 4) # here we will shift entries # of each cell to it's extreme # left row by row # loop to traverse rows for i in range(4): pos = 0 # loop to traverse each column # in respective row for j in range(4): if mat[i][j] != 0: # if cell is non empty then # we will shift it's number to # previous empty cell in that row # denoted by pos variable new_mat[i][pos] = mat[i][j] if j != pos: changed = True pos += 1 # returning new compressed matrix # and the flag variable. return new_mat, changed # function to merge the cells # in matrix after compressing def merge(mat): changed = False for i in range(4): for j in range(3): # if current cell has same value as # next cell in the row and they # are non empty then if mat[i][j] == mat[i][j + 1] and mat[i][j] != 0: # double current cell value and # empty the next cell mat[i][j] = mat[i][j] * 2 mat[i][j + 1] = 0 # make bool variable True indicating # the new grid after merging is # different. changed = True return mat, changed # function to reverse the matrix # means reversing the content of # each row (reversing the sequence) def reverse(mat): new_mat = [] for i in range(4): new_mat.append([]) for j in range(4): new_mat[i].append(mat[i][3 - j]) return new_mat # function to get the transpose # of matrix means interchanging # rows and column def transpose(mat): new_mat = [] for i in range(4): new_mat.append([]) for j in range(4): new_mat[i].append(mat[j][i]) return new_mat # function to update the matrix # if we move / swipe left def move_left(grid): # first compress the grid new_grid, changed1 = compress(grid) # then merge the cells. new_grid, changed2 = merge(new_grid) changed = changed1 or changed2 # again compress after merging. new_grid, temp = compress(new_grid) # return new matrix and bool changed # telling whether the grid is same # or different return new_grid, changed # function to update the matrix # if we move / swipe right def move_right(grid): # to move right we just reverse # the matrix new_grid = reverse(grid) # then move left new_grid, changed = move_left(new_grid) # then again reverse matrix will # give us desired result new_grid = reverse(new_grid) return new_grid, changed # function to update the matrix # if we move / swipe up def move_up(grid): # to move up we just take # transpose of matrix new_grid = transpose(grid) # then move left (calling all # included functions) then new_grid, changed = move_left(new_grid) # again take transpose will give # desired results new_grid = transpose(new_grid) return new_grid, changed # function to update the matrix # if we move / swipe down def move_down(grid): # to move down we take transpose new_grid = transpose(grid) # move right and then again new_grid, changed = move_right(new_grid) # take transpose will give desired # results. new_grid = transpose(new_grid) return new_grid, changed # this file only contains all the logic # functions to be called in main function # present in the other file #Output : Commands are as follows : [END]
2048 Game in Python
https://www.geeksforgeeks.org/2048-game-in-python/
# 2048.py # importing the logic.py file # where we have written all the # logic functions used. import logic # Driver code if __name__ == "__main__": # calling start_game function # to initialize the matrix mat = logic.start_game() while True: # taking the user input # for next step x = input("Press the command : ") # we have to move up if x == "W" or x == "w": # call the move_up function mat, flag = logic.move_up(mat) # get the current state and print it status = logic.get_current_state(mat) print(status) # if game not over then continue # and add a new two if status == "GAME NOT OVER": logic.add_new_2(mat) # else break the loop else: break # the above process will be followed # in case of each type of move # below # to move down elif x == "S" or x == "s": mat, flag = logic.move_down(mat) status = logic.get_current_state(mat) print(status) if status == "GAME NOT OVER": logic.add_new_2(mat) else: break # to move left elif x == "A" or x == "a": mat, flag = logic.move_left(mat) status = logic.get_current_state(mat) print(status) if status == "GAME NOT OVER": logic.add_new_2(mat) else: break # to move right elif x == "D" or x == "d": mat, flag = logic.move_right(mat) status = logic.get_current_state(mat) print(status) if status == "GAME NOT OVER": logic.add_new_2(mat) else: break else: print("Invalid Key Pressed") # print the matrix after each # move. print(mat)
#Output : Commands are as follows :
2048 Game in Python # 2048.py # importing the logic.py file # where we have written all the # logic functions used. import logic # Driver code if __name__ == "__main__": # calling start_game function # to initialize the matrix mat = logic.start_game() while True: # taking the user input # for next step x = input("Press the command : ") # we have to move up if x == "W" or x == "w": # call the move_up function mat, flag = logic.move_up(mat) # get the current state and print it status = logic.get_current_state(mat) print(status) # if game not over then continue # and add a new two if status == "GAME NOT OVER": logic.add_new_2(mat) # else break the loop else: break # the above process will be followed # in case of each type of move # below # to move down elif x == "S" or x == "s": mat, flag = logic.move_down(mat) status = logic.get_current_state(mat) print(status) if status == "GAME NOT OVER": logic.add_new_2(mat) else: break # to move left elif x == "A" or x == "a": mat, flag = logic.move_left(mat) status = logic.get_current_state(mat) print(status) if status == "GAME NOT OVER": logic.add_new_2(mat) else: break # to move right elif x == "D" or x == "d": mat, flag = logic.move_right(mat) status = logic.get_current_state(mat) print(status) if status == "GAME NOT OVER": logic.add_new_2(mat) else: break else: print("Invalid Key Pressed") # print the matrix after each # move. print(mat) #Output : Commands are as follows : [END]
Flames game in Python
https://www.geeksforgeeks.org/python-program-to-implement-simple-flames-game/
# function for removing common characters # with their respective occurrences def remove_match_char(list1, list2): for i in range(len(list1)): for j in range(len(list2)): # if common character is found # then remove that character # and return list of concatenated # list with True Flag if list1[i] == list2[j]: c = list1[i] # remove character from the list list1.remove(c) list2.remove(c) # concatenation of two list elements with * # * is act as border mark here list3 = list1 + ["*"] + list2 # return the concatenated list with True flag return [list3, True] # no common characters is found # return the concatenated list with False flag list3 = list1 + ["*"] + list2 return [list3, False] # Driver code if __name__ == "__main__": # take first name p1 = input("Player 1 name : ") # converted all letters into lower case p1 = p1.lower() # replace any space with empty string p1.replace(" ", "") # make a list of letters or characters p1_list = list(p1) # take 2nd name p2 = input("Player 2 name : ") p2 = p2.lower() p2.replace(" ", "") p2_list = list(p2) # taking a flag as True initially proceed = True # keep calling remove_match_char function # until common characters is found or # keep looping until proceed flag is True while proceed: # function calling and store return value ret_list = remove_match_char(p1_list, p2_list) # take out concatenated list from return list con_list = ret_list[0] # take out flag value from return list proceed = ret_list[1] # find the index of "*" / border mark star_index = con_list.index("*") # list slicing perform # all characters before * store in p1_list p1_list = con_list[:star_index] # all characters after * store in p2_list p2_list = con_list[star_index + 1 :] # count total remaining characters count = len(p1_list) + len(p2_list) # list of FLAMES acronym result = ["Friends", "Love", "Affection", "Marriage", "Enemy", "Siblings"] # keep looping until only one item # is not remaining in the result list while len(result) > 1: # store that index value from # where we have to perform slicing. split_index = count % len(result) - 1 # this steps is done for performing # anticlock-wise circular fashion counting. if split_index >= 0: # list slicing right = result[split_index + 1 :] left = result[:split_index] # list concatenation result = right + left else: result = result[: len(result) - 1] # print final result print("Relationship status :", result[0])
#Input : player1 name : AJAY player 2 name : PRIYA
Flames game in Python # function for removing common characters # with their respective occurrences def remove_match_char(list1, list2): for i in range(len(list1)): for j in range(len(list2)): # if common character is found # then remove that character # and return list of concatenated # list with True Flag if list1[i] == list2[j]: c = list1[i] # remove character from the list list1.remove(c) list2.remove(c) # concatenation of two list elements with * # * is act as border mark here list3 = list1 + ["*"] + list2 # return the concatenated list with True flag return [list3, True] # no common characters is found # return the concatenated list with False flag list3 = list1 + ["*"] + list2 return [list3, False] # Driver code if __name__ == "__main__": # take first name p1 = input("Player 1 name : ") # converted all letters into lower case p1 = p1.lower() # replace any space with empty string p1.replace(" ", "") # make a list of letters or characters p1_list = list(p1) # take 2nd name p2 = input("Player 2 name : ") p2 = p2.lower() p2.replace(" ", "") p2_list = list(p2) # taking a flag as True initially proceed = True # keep calling remove_match_char function # until common characters is found or # keep looping until proceed flag is True while proceed: # function calling and store return value ret_list = remove_match_char(p1_list, p2_list) # take out concatenated list from return list con_list = ret_list[0] # take out flag value from return list proceed = ret_list[1] # find the index of "*" / border mark star_index = con_list.index("*") # list slicing perform # all characters before * store in p1_list p1_list = con_list[:star_index] # all characters after * store in p2_list p2_list = con_list[star_index + 1 :] # count total remaining characters count = len(p1_list) + len(p2_list) # list of FLAMES acronym result = ["Friends", "Love", "Affection", "Marriage", "Enemy", "Siblings"] # keep looping until only one item # is not remaining in the result list while len(result) > 1: # store that index value from # where we have to perform slicing. split_index = count % len(result) - 1 # this steps is done for performing # anticlock-wise circular fashion counting. if split_index >= 0: # list slicing right = result[split_index + 1 :] left = result[:split_index] # list concatenation result = right + left else: result = result[: len(result) - 1] # print final result print("Relationship status :", result[0]) #Input : player1 name : AJAY player 2 name : PRIYA [END]
Pok??????mon Training
https://www.geeksforgeeks.org/python-pokemon-training-game/
# python code to train pokemon powers = [3, 8, 9, 7] mini, maxi = 0, 0 for power in powers: if mini == 0 and maxi == 0: mini, maxi = powers[0], powers[0] print(mini, maxi) else: mini = min(mini, power) maxi = max(maxi, power) print(mini, maxi) # Time Complexity is O(N) with Space Complexity O(1)
#Input :
Pok??????mon Training # python code to train pokemon powers = [3, 8, 9, 7] mini, maxi = 0, 0 for power in powers: if mini == 0 and maxi == 0: mini, maxi = powers[0], powers[0] print(mini, maxi) else: mini = min(mini, power) maxi = max(maxi, power) print(mini, maxi) # Time Complexity is O(N) with Space Complexity O(1) #Input : [END]
Rock Paper Scissor game in Python
https://www.geeksforgeeks.org/python-program-implement-rock-paper-scissor-game/
# import random module import random # print multiline instruction # performstring concatenation of string print( "Winning rules of the game ROCK PAPER SCISSORS are :\n" + "Rock vs Paper -> Paper wins \n" + "Rock vs Scissors -> Rock wins \n" + "Paper vs Scissors -> Scissor wins \n" ) while True: print("Enter your choice \n 1 - Rock \n 2 - Paper \n 3 - Scissors \n") # take the input from user choice = int(input("Enter your choice :")) # OR is the short-circuit operator # if any one of the condition is true # then it return True value # looping until user enter invalid input while choice > 3 or choice < 1: choice = int(input("Enter a valid choice please ???")) # initialize value of choice_name variable # corresponding to the choice value if choice == 1: choice_name = "Rock" elif choice == 2: choice_name = "Paper" else: choice_name = "Scissors" # print user choice print("User choice is \n", choice_name) print("Now its Computers Turn....") # Computer chooses randomly any number # among 1 , 2 and 3. Using randint method # of random module comp_choice = random.randint(1, 3) # looping until comp_choice value # is equal to the choice value while comp_choice == choice: comp_choice = random.randint(1, 3) # initialize value of comp_choice_name # variable corresponding to the choice value if comp_choice == 1: comp_choice_name = "rocK" elif comp_choice == 2: comp_choice_name = "papeR" else: comp_choice_name = "scissoR" print("Computer choice is \n", comp_choice_name) print(choice_name, "Vs", comp_choice_name) # we need to check of a draw if choice == comp_choice: print("Its a Draw", end="") result = "DRAW" # condition for winning if choice == 1 and comp_choice == 2: print("paper wins =>", end="") result = "papeR" elif choice == 2 and comp_choice == 1: print("paper wins =>", end="") result = "Paper" if choice == 1 and comp_choice == 3: print("Rock wins =>\n", end="") result = "Rock" elif choice == 3 and comp_choice == 1: print("Rock wins =>\n", end="") result = "rocK" if choice == 2 and comp_choice == 3: print("Scissors wins =>", end="") result = "scissoR" elif choice == 3 and comp_choice == 2: print("Scissors wins =>", end="") result = "Rock" # Printing either user or computer wins or draw if result == "DRAW": print("<== Its a tie ==>") if result == choice_name: print("<== User wins ==>") else: print("<== Computer wins ==>") print("Do you want to play again? (Y/N)") # if user input n or N then condition is True ans = input().lower if ans == "n": break # after coming out of the while loop # we print thanks for playing print("thanks for playing")
#Output : Winning Rules as follows:
Rock Paper Scissor game in Python # import random module import random # print multiline instruction # performstring concatenation of string print( "Winning rules of the game ROCK PAPER SCISSORS are :\n" + "Rock vs Paper -> Paper wins \n" + "Rock vs Scissors -> Rock wins \n" + "Paper vs Scissors -> Scissor wins \n" ) while True: print("Enter your choice \n 1 - Rock \n 2 - Paper \n 3 - Scissors \n") # take the input from user choice = int(input("Enter your choice :")) # OR is the short-circuit operator # if any one of the condition is true # then it return True value # looping until user enter invalid input while choice > 3 or choice < 1: choice = int(input("Enter a valid choice please ???")) # initialize value of choice_name variable # corresponding to the choice value if choice == 1: choice_name = "Rock" elif choice == 2: choice_name = "Paper" else: choice_name = "Scissors" # print user choice print("User choice is \n", choice_name) print("Now its Computers Turn....") # Computer chooses randomly any number # among 1 , 2 and 3. Using randint method # of random module comp_choice = random.randint(1, 3) # looping until comp_choice value # is equal to the choice value while comp_choice == choice: comp_choice = random.randint(1, 3) # initialize value of comp_choice_name # variable corresponding to the choice value if comp_choice == 1: comp_choice_name = "rocK" elif comp_choice == 2: comp_choice_name = "papeR" else: comp_choice_name = "scissoR" print("Computer choice is \n", comp_choice_name) print(choice_name, "Vs", comp_choice_name) # we need to check of a draw if choice == comp_choice: print("Its a Draw", end="") result = "DRAW" # condition for winning if choice == 1 and comp_choice == 2: print("paper wins =>", end="") result = "papeR" elif choice == 2 and comp_choice == 1: print("paper wins =>", end="") result = "Paper" if choice == 1 and comp_choice == 3: print("Rock wins =>\n", end="") result = "Rock" elif choice == 3 and comp_choice == 1: print("Rock wins =>\n", end="") result = "rocK" if choice == 2 and comp_choice == 3: print("Scissors wins =>", end="") result = "scissoR" elif choice == 3 and comp_choice == 2: print("Scissors wins =>", end="") result = "Rock" # Printing either user or computer wins or draw if result == "DRAW": print("<== Its a tie ==>") if result == choice_name: print("<== User wins ==>") else: print("<== Computer wins ==>") print("Do you want to play again? (Y/N)") # if user input n or N then condition is True ans = input().lower if ans == "n": break # after coming out of the while loop # we print thanks for playing print("thanks for playing") #Output : Winning Rules as follows: [END]
Taking Screenshots using pyscreenshot in Python
https://www.geeksforgeeks.org/taking-screenshots-using-pyscreenshot-in-python/
# Program to take screenshot import pyscreenshot # To capture the screen image = pyscreenshot.grab() # To display the captured screenshot image.show() # To save the screenshot image.save("GeeksforGeeks.png")
#Output : pip install pyscreenshot
Taking Screenshots using pyscreenshot in Python # Program to take screenshot import pyscreenshot # To capture the screen image = pyscreenshot.grab() # To display the captured screenshot image.show() # To save the screenshot image.save("GeeksforGeeks.png") #Output : pip install pyscreenshot [END]
Taking Screenshots using pyscreenshot in Python
https://www.geeksforgeeks.org/taking-screenshots-using-pyscreenshot-in-python/
# Program for partial screenshot import pyscreenshot # im=pyscreenshot.grab(bbox=(x1,x2,y1,y2)) image = pyscreenshot.grab(bbox=(10, 10, 500, 500)) # To view the screenshot image.show() # To save the screenshot image.save("GeeksforGeeks.png")
#Output : pip install pyscreenshot
Taking Screenshots using pyscreenshot in Python # Program for partial screenshot import pyscreenshot # im=pyscreenshot.grab(bbox=(x1,x2,y1,y2)) image = pyscreenshot.grab(bbox=(10, 10, 500, 500)) # To view the screenshot image.show() # To save the screenshot image.save("GeeksforGeeks.png") #Output : pip install pyscreenshot [END]
Desktop Notifier in Python
https://www.geeksforgeeks.org/desktop-notifier-python/
import requests import xml.etree.ElementTree as ET # url of news rss feed RSS_FEED_URL = "http://www.hindustantimes.com/rss/topnews/rssfeed.xml" def loadRSS(): """ utility function to load RSS feed """ # create HTTP request response object resp = requests.get(RSS_FEED_URL) # return response content return resp.content def parseXML(rss): """ utility function to parse XML format rss feed """ # create element tree root object root = ET.fromstring(rss) # create empty list for news items newsitems = [] # iterate news items for item in root.findall("./channel/item"): news = {} # iterate child elements of item for child in item: # special checking for namespace object content:media if child.tag == "{http://search.yahoo.com/mrss/}content": news["media"] = child.attrib["url"] else: news[child.tag] = child.text.encode("utf8") newsitems.append(news) # return news items list return newsitems def topStories(): """ main function to generate and return news items """ # load rss feed rss = loadRSS() # parse XML newsitems = parseXML(rss) return newsitems
#Output : {'description': 'Months after it was first reported, the feud between Dwayne Johnson and
Desktop Notifier in Python import requests import xml.etree.ElementTree as ET # url of news rss feed RSS_FEED_URL = "http://www.hindustantimes.com/rss/topnews/rssfeed.xml" def loadRSS(): """ utility function to load RSS feed """ # create HTTP request response object resp = requests.get(RSS_FEED_URL) # return response content return resp.content def parseXML(rss): """ utility function to parse XML format rss feed """ # create element tree root object root = ET.fromstring(rss) # create empty list for news items newsitems = [] # iterate news items for item in root.findall("./channel/item"): news = {} # iterate child elements of item for child in item: # special checking for namespace object content:media if child.tag == "{http://search.yahoo.com/mrss/}content": news["media"] = child.attrib["url"] else: news[child.tag] = child.text.encode("utf8") newsitems.append(news) # return news items list return newsitems def topStories(): """ main function to generate and return news items """ # load rss feed rss = loadRSS() # parse XML newsitems = parseXML(rss) return newsitems #Output : {'description': 'Months after it was first reported, the feud between Dwayne Johnson and [END]