How to get first key in Dictionary – Python | Get the First Key in Python Dictionary

How to get first key in Dictionary – Python

How to get First Key in a Dictionary Python: In this tutorial, we will discuss different ways to get the first key in a dictionary. Later, we will see & learn how to choose the first N Keys of a dictionary in Python.

Get the first key from a dictionary using keys() method

Python print first item in dictionary: Dictionary stores elements in key-value pairs.Dictionary act as a container in python. Dictionary provided keys() function which we will use to fetch all keys in it and after that we select the first key from a sequence.

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first key in a dictionary
first_key = list(word_freq.keys())[0]
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

Get first element of dictionary python: In the above example, you can see that first we have fetched all dictionary elements and by using indexing we find out the first key value.

Do Refer:

Here is another way to do the same,

Another Way for How to get First Key in Dictionary Python

Print keys of dictionary python: By using this method, it will convert all keys of the dictionary to a list and then we can select the first element from the list.

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first ket in a dictionary
first_key = list(word_freq)[0]
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

In the above example, we didn’t call the keys() function. We created a list of keys from the dictionary and selected the first item from it.

Get first key in a dictionary using iter() & next()

What we have done above that was not a perfect solution because first, we created a list and then fetch the first key in a dictionary. It is very difficult to apply that method in a large number of dictionaries. First, we iterate the object of keys using the iter() function then we apply the next() function on it for getting the first element.

Get first key in a dictionary using iter() & next()

This is an efficient solution because didn’t iterate over all the keys in a dictionary, we just selected the first one.

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first key in a dictionary
first_key = next(iter(word_freq))
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

Get the First Key in Dictionary Using list() Function

Also, there is a possible way to convert the dict type into a list using thelist() function at first and later get the first key at the 0th index of the dictionary.

my_dict = { 'Russia': 2, 'New York': 1, 'Lahore': 6, 'Tokyo': 11}

print(list(my_dict.keys())[0])

Result:

Russia

Get the First Key in Dictionary Using for Loop

One more easiest way to get the initial key in a dictionary is using theforloop. After getting the first key of the dictionary break the loop.

Let’s see an example on it:

my_dict = { 'London': 2, 'New York': 1, 'Lahore': 6, 'Tokyo': 11}

for key, value in my_dict.items():
  print(key)
  break

Output:

London

Get first N keys from a Dictionary in Python

To select the first N keys from a dictionary, convert the keys of a dictionary to a list and then select the first N entries from that. For example, let’s see how to select the first 3 keys from a dictionary,

# Dictionary of string and int
word_freq = {
    'Anni': 56,
    "is": 23,
    'my': 43,
    'Fav': 78,
    'Person': 11
}
# Get the first ket in a dictionary
first_key = list(word_freq)[0]
print('First Key of dictionary:')
print(first_key)

Output:

First Key of dictionary:
Anni

Conclusion on Get First value in a dictionary of string and int

In this article, we have seen discuss different ways to find out the first key of a dictionary in python. All these dictionary keys methods in python help to find easily the key value in a dictionary of string and int word_freq. Get first key of the dictionary in python information completely from this article.

Compiling C++ with Debug Symbols – gdb debugger Tutorial & Examples

g++ gdb: In this article we are going to discuss how to debugging using gdb debugger in C++.

gdb debugger is an application for execute C or C++ program to check the code working and it’s crashes.There are so many task which can be done using gdb debugger,like check prgram,run code,test new conditions and find out errors.

Compile Code with Debug Symbols

We should debug C or C++ program in debug mode.We should use -g option in it.

Below is our first step to debug program using gdb,

g++ -g filename.cpp -o Sample

Now there is two way to debug using gdb debugger;

1.Debugging with executable name,

gdb filename

It will read symbols from ‘filename’ after this type below command;

(gdb) run

2.Start gdb alone without debugging-

gdb

Now give the file name for execution,

(gdb) file filename

After that your application start debugging in debug mode.

Passing Command Line Arguments while debugging

We can also pass command argument at the time of debugging.For this we use below command;

Reading symbols from filename...done.
(gdb) run 1 2 3

There are so many different command in gdb debugger to know them you can run help command,

(gdb) help

It will show you all command list and their working,like below;

Command Description
help Provides information about a topic or commands you can use
file Indicates which file to debug
run Executes the program under GDB
break Adds breakpoints to stop the program execution temporary
delete Deletes breakpoints
clear Deletes breakpoints for a specific function
continue Resets the program after a breakpoint triggers
step Runs the current source line and stops before executing the next one
ext Runs the current source line. However, if the line is a function call, the debugger will fully execute the function before the execution stops again
until Runs the current source line. If you are at the beginning of a loop, the debugger runs until the loop ends
list Prints a certain list from the source code
print Prints values of certain expressions

How do I exit the debugging

For exiting you have to write quit command and you will be out from debug mode,

(gdb) quit

And if you again want to come in debug mode then you will just press “Ctrl-C”.

Conclusion:

In this article we have discussed how to debugging using gdb debugger in C++.Thank you!

How to execute python program – How to Run a Python Script

How to execute python program: Python is not just one of the leading programming languages, but also a top choice for dealing with big data and data science projects. The fact that it is among the easiest languages to learn makes the high-level, interpreted, general-purpose programming language even more lucrative.

For using Python on a system, the user first needs to install the Python environment. It will also install the Python interpreter, which is responsible for carrying out Python code execution. It is possible to run Python code directly from the terminal using the Python interpreter.

Python is a well known high-level programming language. The Python script is basically a file containing code written in Python. The file containing python script has the extension ‘.py’ or can also have the extension ‘.pyw’ if it is being run on a windows machine. To run a python script, we need a python interpreter that needs to be downloaded and installed.

Scripts vs Modules:

A Python script is a collection of commands in a file designed to be executed like a program. The file can of course contain functions and import various modules, but the idea is that it will be run or executed from the command line or from within a Python interactive shell to perform a specific task. Often a script first contains a set of function definitions and then has the main program that might call the functions.

Scripts are always processed by some kind of interpreter, which is responsible for executing each command sequentially.

A plain text file containing Python code that is intended to be directly executed by the user is usually called script, which is an informal term that means top-level program file.

On the other hand, a plain text file, which contains Python code that is designed to be imported and used from another Python file, is called module.

So, the main difference between a module and a script is that modules are meant to be imported, while scripts are made to be directly executed.

Different ways to run Python Script:

  1. Interactive Mode
  2. Command Line
  3. Text Editor
  4. IDE (PyCharm)

 

1.Interactive Mode:

Interactive mode, also known as the REPL provides us with a quick way of running blocks or a single line of Python code. The code executes via the Python shell, which comes with Python installation. Interactive mode is handy when you just want to execute basic Python commands or you are new to Python programming and just want to get your hands dirty with this beautiful language.

To access the Python shell, open the terminal of your operating system and then type “python”. Press the enter key and the Python shell will appear. This is the same Python executable you use to execute scripts, which comes installed by default on Mac and Unix-based operating systems.

How to Run a Python Script_interactive mode
The >>> indicates that the Python shell is ready to execute and send your commands to the Python interpreter. The result is immediately displayed on the Python shell as soon as the Python interpreter interprets the command.

To run your Python statements, just type them and hit the enter key. You will get the results immediately, unlike in script mode. For example, to print the text “Hello World”, we can type the following:

Interactive Mode output

2.Command Line:

To run a Python script store in a ‘.py’ file in command line, we have to write ‘python’ keyword before the file name in the command prompt.

python hello.py

You can write your own file name in place of ‘hello.py’.

Using command line
3.Text Editor :

Python’s standard distribution includes IDLE as the default IDE, and you can use it to write, debug, modify, and run your modules and scripts.

Other IDEs such as Eclipse-PyDev, PyCharm, Eric, and NetBeans also allow you to run Python scripts from inside the environment.

Advanced text editors like Sublime Text andVisual Studio Code also allow you to run your scripts.

4.IDE (PyCharm):

To run Python script on a IDE like PyCharm you will have to do the following:

  • Create a new project.
  • Give a name to that project as ‘NewProject’ and click on Create.
  • Select the root directory with the project name we specified in the last step. Right click on it, go in New and click on ‘Python file’ option. Then give the name of the file as ‘hello’ (you can specify any name as per your project requirement). This will create a ‘hello.py’ file in the project root directory.
    Note: You don’t have to specify the extension as it will take it automatically.

Using IDE (PyCharm)
Now write the below Python script to print the message:

print('Hello World !')

Using IDE (PyCharm) output

Conclusion:

With the reading of this tutorial, you have acquired the knowledge and skills you need to be able to run Python scripts and code in several ways and in a variety of situations and development environments.

Python timestamp to string – Python: How to convert a timestamp string to a datetime object using datetime.strptime()

Python- How to convert a timestamp string to a datetime object using datetime.strptime()

Python timestamp to string: In this tutorial, we will learn how to convert a timestamp string to a datetime object using datetime.strptime(). Also, you can understand how to to create a datetime object from a string in Python with examples below.

String to a DateTime object using datetime.strptime()

Python convert timestamp to string: Thestrptime()method generates a datetime object from the given string.

Datetime module provides a datetime class that has a method to convert string to a datetime object.

Syntax:

datetime.strptime(date_string, format)

So in the above syntax, you can see that it accepts a string containing a timestamp. It parses the string according to format codes and returns a datetime object created from it.

First import datetime class from datetime module to use this,

from datetime import datetime

Also Read:

Complete Format Code List

Format Codes Description Example
%d Day of the month as a zero-padded decimal number 01, 02, 03, 04 …, 31
%a Weekday as the abbreviated name Sun, Mon, …, Sat
%A Weekday as full name Sunday, Monday, …, Saturday
%m Month as a zero-padded decimal number 01, 02, 03, 04 …, 12
%b Month as an abbreviated name Jan, Feb, …, Dec
%B Month as full name January, February, …, December
%y A Year without century as a zero-padded decimal number 00, 01, …, 99
%Y A Year with a century as a decimal number 0001, …, 2018, …, 9999
%H Hour (24-hour clock) as a zero-padded decimal number 01, 02, 03, 04 …, 23
%M Minute as a zero-padded decimal number 01, 02, 03, 04 …, 59
%S Second as a zero-padded decimal number 01, 02, 03, 04 …, 59
%f Microsecond as a decimal number, zero-padded on the left 000000, 000001, …, 999999
%I Hour (12-hour clock) as a zero-padded decimal number 01, 02, 03, 04 …, 12
%p Locale’s equivalent of either AM or PM AM, PM
%j Day of the year as a zero-padded decimal number 01, 02, 03, 04 …, 366

How strptime() works?

In thestrptime()class method, it takes two arguments:

  • string (that be converted to datetime)
  • format code

In the accordance with the string and format code used, the method returns its equivalent datetime object.

Let’s see the following example, to understand how it works:

python strptime method example

where,

%d – Represents the day of the month. Example: 01, 02, …, 31
%B – Month’s name in full. Example: January, February etc.
%Y – Year in four digits. Example: 2018, 2019 etc.

Examples of converting a Time String in the format codes using strptime() method

Timestamp to string python: Just have a look at the few examples on how to convert timestamp string to a datetime object using datetime.strptime() in Python and gain enough knowledge on it.

Example 1:

Let’s take an example,

from datetime import datetime
datetimeObj = datetime.strptime('2021-05-17T15::11::45.456777', '%Y-%m-%dT%H::%M::%S.%f')
print(datetimeObj)
print(type(datetimeObj))

Output:

2021-05-17 15:11:45.456777
<class 'datetime.datetime'>

So in the above example, you can see that we have converted a time string in the format “YYYY-MM-DDTHH::MM::SS.MICROS” to a DateTime object.

Let’s take another example,

Example 2:

from datetime import datetime
datetimeObj = datetime.strptime('17/May/2021 14:12:22', '%d/%b/%Y %H:%M:%S')
print(datetimeObj)
print(type(datetimeObj))

Output:

2021-05-17 14:12:22
<class 'datetime.datetime'>

So this is the other way to show timestamp here we have converted a time string in the format “DD/MM/YYYY HH::MM::SS” to a datetime object.

Example 3:

If we want to show the only date in this format “DD MMM YYYY”. We do like this,

from datetime import datetime
datetimeObj = datetime.strptime('17 May 2021', '%d %b %Y')
# Get the date object from datetime object
dateObj = datetimeObj.date()
print(dateObj)
print(type(dateObj))

Output:

2021-05-17
<class 'datetime.date'>

Example 4:

So if we want to show only time “‘HH:MM:SS AP‘” in this format. We will do like that,

from datetime import datetime
datetimeObj = datetime.strptime('08:12:22 PM', '%I:%M:%S %p') 
# Get the time object from datetime object 
timeObj = datetimeObj.time()
print(timeObj) 
print(type(timeObj))

Output:

20:12:22
<class 'datetime.time'>

Example 5:

If we want to show our timestamp in text format. We will execute like that,

from datetime import datetime
textStr = "On January the 17th of 2021 meet me at 8 PM"
datetimeObj = datetime.strptime(textStr, "On %B the %dth of %Y meet me at %I %p")
print(datetimeObj)

Output:

2021-01-17 20:00:00

Conclusion:

So in the above tutorial, you can see that we have shown different methods of how to convert a timestamp string to a datetime object using datetime.strptime(). Thank you!

Pad string with spaces python – Python: How to pad strings with zero, space or some other character?

Python-How to pad strings with zero, space or some other character

Pad string with spaces python: In this tutorial, we are going to discuss how to do padding of strings using zero, space, or some other character. Also, you can get complete knowledge of the methods used for padding strings in Python. So, let’s get started on learning How to pad strings with Zero, Space, or some other character.

Types of Padding in Python

There are two types of padding:

  1. Left padding
  2. Right padding

1. Left padding of string in Python

Python pad string with spaces: Left padding means adding a given character on the left side of a string.

For Example – If we pad three zeros in string 6 i.e, ‘0006’, or if we pad three space in string i.e,’6′

numStr = "6"
print('Original String :', numStr)
# Left pad the string with 0 to make it's length 4
numStr = numStr.zfill(4)
print('Updated String :' , numStr)

Output:

Original String : 6
Updated String : 0006

So in the above example, we have used'string.zfill(s, width)'to pad a given string on the left with zeros (0).

Also Check:

Left pad a string with space using string.rjust()

Python zero pad: In this, we are going to use string.rjust() to add space in a given string.

numStr = "6"
print('Original String :', numStr)
# Make string right justified of length 4 by padding 3 spaces to left
numStr = numStr.rjust(4, ' ')
print('Updated String :', numStr)

Output:

Original String : 6
Updated String :    6

Left pad a string with some character using string.rjust()

Python pad string: For adding any character to our string we will use string.rjust() and pass that character in it.

numStr = "6"
print('Original String :', numStr)
# Make string right justified of length 4 by padding 3 '-' to left
numStr = numStr.rjust(4, '-')
print('Updated String :', numStr)

Output:

Original String : 6
Updated String : ---6

2. Right padding of string in Python

Python pad string: Right padding means adding a given character on the right side of the string.

Example- If we have a number string i.e. “ram”. Now we want to convert this string of length 3 to a string of length 6 by,

  • Right padding three zeros to the string i.e. “ram000”
  • Right padding three-space to the string i.e. “ram “
  • Right padding three characters to the string i.e. “ram—“

Right pad a string with zeros using string.ljust()

string.ljust() is used for padding a given character to the right of string to make its a length equal to the given width.

numStr = "67"
print('Original String :', numStr)
# Make string left justified of length 5 by padding 3 0s to the right of it
numStr = numStr.ljust(5, '0')
print('Updated String :', numStr)

Output:

Original String : 67
Updated String : 67000

Right pad a string with space using string.ljust()

In this, we will use string.ljust() to pad given character,

userName = "Shikha"
print('Original String :', userName)
# Make string left justified of length 7 by padding 3 spaces to the right of it
userName = userName.ljust(7, ' ')
print('Updated String :' , userName, 'is')

Here 3 spaces are padded to the right of the given string to make its length 9.

Output:

Original String : Shikha
Updated String : Shikha   is

Right pad a string with some character using string.ljust()

We can pass a character in string.ljust(s, width[, fillchar]) to right pad the given string by that passed character.

userName = "shikha"
print('Original String :', userName)
# Make string left justified of length 7 by padding 3 '-' to the right of it
userName = userName.ljust(7, '-')
print('Updated String :' , userName)

Output:

Here, three ‘-‘ are padded to the right of the given string to make its length 9.

Original String : shikha
Updated String : shikha---

Conclusion:

In this article, you have seen that how to do padding of strings using zero, space, or some other character.

Thank you!

CPP 11 Multithreading – Part 2: Joining and Detaching Threads | std::thread::join() & std::thread::detach() Methods with Examples

CPP 11 Multithreading – Part 2- Joining and Detaching Threads

Thread join c++: In the previous article, we have discussed about How to trim strings in C++ using Boost String Algorithm Library. Let us learn how to find Multithreading – Part 2 in C++ Program.

Let’s discover this tutorial for getting more knowledge about C++11 Multithreading Part-2.  Here we are going to learn what is joining and detaching threads of std::thread. Apart from that, you may also see the explanation of std::thread::join() & std::thread::detach() Methods with Examples. So, stay tuned to this tutorial easily via available quick links.

Joining Threads with std::thread::join()

Std thread join: When the first thread is started then the other thread that is going to start yet should wait for the first thread to finish. For this, another we need to call the join() function on the std::thread object.

Syntax:

std::thread th(funcPtr);

// Some Code

th.join();

Suppose Main Thread has to start 10 Worker Threads and after starting all these threads, the main function will wait for them to finish. After joining all the threads the main function will continue.

So, let’s take an example. There is one main thread and some worker threads after joining all the threads the main function will continue. The main function will wait for them to finish.

#include <iostream>
#include <thread>
#include <algorithm>
#include <vector>
#include <functional>
class WorkerThread
{
public:
    void operator()()     
    {
        std::cout<<"Worker Thread "<<std::this_thread::get_id()<<" is Executing"<<std::endl;
    }
};
int main()  
{
    std::vector<std::thread> threadList;
    for(int i = 0; i < 10; i++)
    {
        threadList.push_back( std::thread( WorkerThread() ) );
    }
    // Now wait for all the worker thread to finish i.e.
    // Call join() function on each of the std::thread object
    std::cout<<"wait for all the worker thread to finish"<<std::endl;
    std::for_each(threadList.begin(),threadList.end(), std::mem_fn(&std::thread::join));
    std::cout<<"Exiting from Main Thread"<<std::endl;
    return 0;
}

Detaching Threads using std::thread::detach()

Detached threads are background threads sometimes also called daemon threads. To detach a thread we need to call std::detach() function on std::thread object. ie.,

std::thread th(funcPtr);
th.detach();

Once you call the detach(), then the std::thread object is no longer connected with the actual thread of execution.

Also Check:

Be cautious with calling detach() and join() on Thread Handles

We have to be careful on calling detach() and join() on thread handles. We are going to discuss some cases below for this:

Case 1: Never call join() or detach() on std::thread object with no associated executing thread

std::thread threadObj( (WorkerThread()) );
   threadObj.join();
   threadObj.join(); // It will cause Program to Terminate

When a join() function called on a thread object, join returns 0 then that ‘td::thread’ object has no associated thread with it. If the join() function again called on such an object then it will cause the program to Terminate. Similarly, detach() function will work.

Syntax:

std::thread threadObj( (WorkerThread()) );
   threadObj.detach();
   threadObj.detach(); // It will cause Program to Terminate

Before calling join() or detach() we should check if the thread is join-able every time or not,

std::thread threadObj( (WorkerThread()) );
   if(threadObj.joinable())
   {
       std::cout<<"Detaching Thread "<<std::endl;
       threadObj.detach();
   }
   if(threadObj.joinable())    
   {
       std::cout<<"Detaching Thread "<<std::endl;
       threadObj.detach();
   }
   
   std::thread threadObj2( (WorkerThread()) );
   if(threadObj2.joinable())
   {
       std::cout<<"Joining Thread "<<std::endl;
       threadObj2.join();
   }
   if(threadObj2.joinable())    
   {
       std::cout<<"Joining Thread "<<std::endl;
       threadObj2.join();
   }

Case 2: Never forget to call either join or detach on a std::thread object with associated executing thread

In this case, if neither join nor detach is called with a ‘std::thread’ object that has associated executing thread then during that object’s destruct-or it will terminate the program.

#include <iostream>
#include <thread>
#include <algorithm>
class WorkerThread
{
public:
    void operator()()     
    {
        std::cout<<"Worker Thread "<<std::endl;
    }
};
int main()  
{
    std::thread threadObj( (WorkerThread()) );
    // Program will terminate as we have't called either join or detach with the std::thread object.
    // Hence std::thread's object destructor will terminate the program
    return 0;
}

Similarly, we should not forget to call either join() or detach() in case of exceptions.

To prevent this with we should use Resource Acquisition Is Initialization (RAII) which is show below,

#include <iostream>
#include <thread>
class ThreadRAII
{
    std::thread & m_thread;
    public:
        ThreadRAII(std::thread  & threadObj) : m_thread(threadObj)
        {
            
        }
        ~ThreadRAII()
        {
            // Check if thread is joinable then detach the thread
            if(m_thread.joinable())
            {
                m_thread.detach();
            }
        }
};
void thread_function()
{
    for(int i = 0; i < 10000; i++);
        std::cout<<"thread_function Executing"<<std::endl;
}
 
int main()  
{
    std::thread threadObj(thread_function);
    
    // If we comment this Line, then program will crash
    ThreadRAII wrapperObj(threadObj);
    return 0;
}

Conclusion:

In this article, we have discussed completely regarding C++11 Multithreading joining and detaching threads of std::thread and some risk cases. Thank you!

How to create a discord bot python – How to Make a Discord Bot Python

How to create a discord bot python: In a world where video games are so important to so many people, communication and community around games are vital. Discord offers both of those and more in one well-designed package. In this tutorial, you’ll learn how to make a Discord bot in Python so that you can make the most of this fantastic platform.

What Is Discord?

Discord bot python tutorial: Discord is a voice and text communication platform for gamers.

Players, streamers, and developers use Discord to discuss games, answer questions, chat while they play, and much more. It even has a game store, complete with critical reviews and a subscription service. It is nearly a one-stop shop for gaming communities.

While there are many things you can build using Discord’s APIs this tutorial will focus on a particular learning outcome: how to make a Discord bot in Python.

What Is a Bot?

Python discord bot tutorial: Discord is growing in popularity. As such, automated processes, such as banning inappropriate users and reacting to user requests are vital for a community to thrive and grow.

Automated programs that look and act like users and automatically respond to events and commands on Discord are called bot users. Discord bot users (or just bots) have nearly unlimited application.

How to Make a Discord Bot in the Developer Portal:

Before you can dive into any Python code to handle events and create exciting automations, you need to first create a few Discord components:

  1. An account
  2. An application
  3. A bot
  4. A guild

You’ll learn more about each piece in the following sections.

Once you’ve created all of these components, you’ll tie them together by registering your bot with your guild.

Creating a Discord Account

Create discord bot python: The first thing you’ll see is a landing page where you’ll need to either login, if you have an existing account, or create a new account:

Creating-a-Discord-Account

If you need to create a new account, then click on the Register button below Login and enter your account information.

Once you’re finished, you’ll be redirected to the Developer Portal home page, where you’ll create your application.

Creating-a-Discord-Account-login

Creating an Application:

How to make a discord bot with python: An application allows you to interact with Discord’s APIs by providing authentication tokens, designating permissions, and so on.

To create a new application, select New Application:

Creating-a-Discord-Account-application

Next, you’ll be prompted to name your application. Select a name and click Create:

Creating-a-Discord-Account-login-creating

Congratulations! You made a Discord application. On the resulting screen, you can see information about your application:

Creating-a-Discord-Account-login-done.png

Keep in mind that any program that interacts with Discord APIs requires a Discord application, not just bots. Bot-related APIs are only a subset of Discord’s total interface.

However, since this tutorial is about how to make a Discord bot, navigate to the Bot tab on the left-hand navigation list.

Creating a Bot

As you learned in the previous sections, a bot user is one that listens to and automatically reacts to certain events and commands on Discord.

For your code to actually be manifested on Discord, you’ll need to create a bot user. To do so, select Add Bot:

Creating-a-Discord-boat

Once you confirm that you want to add the bot to your application, you’ll see the new bot user in the portal:

Creating-a-Discord-account-new-boat-user

Now, the bot’s all set and ready to go, but to where?

A bot user is not useful if it’s not interacting with other users. Next, you’ll create a guild so that your bot can interact with other users.

Creating a Guild

A guild (or a server, as it is often called in Discord’s user interface) is a specific group of channels where users congregate to chat.

You’d start by creating a guild. Then, in your guild, you could have multiple channels, such as:

  • General Discussion: A channel for users to talk about whatever they want
  • Spoilers, Beware: A channel for users who have finished your game to talk about all the end game reveals
  • Announcements: A channel for you to announce game updates and for users to discuss them

Once you’ve created your guild, you’d invite other users to populate it.

So, to create a guild, head to your Discord home page:

Creating-a-Discord-home-page

From this home page, you can view and add friends, direct messages, and guilds. From here, select the + icon on the left-hand side of the web page to Add a Server:

This will present two options, Create a server and Join a Server. In this case, select Create a server and enter a name for your guild.

Creating-a-Discord-creating-a-server

Once you’ve finished creating your guild, you’ll be able to see the users on the right-hand side and the channels on the left.

The final step on Discord is to register your bot with your new guild.

Adding a Bot to a Guild

A bot can’t accept invites like a normal user can. Instead, you’ll add your bot using the OAuth2 protocol.

To do so, head back to the Developer Portal and select the OAuth2 page from the left-hand navigation:

Add your bot using the OAuth2 protocol.

From this window, you’ll see the OAuth2 URL Generator.

This tool generates an authorization URL that hits Discord’s OAuth2 API and authorizes API access using your application’s credentials.

In this case, you’ll want to grant your application’s bot user access to Discord APIs using your application’s OAuth2 credentials.

To do this, scroll down and select bot from the SCOPES options and Administrator from BOT PERMISSIONS:

BOT PERMISSIONS

Now, Discord has generated your application’s authorization URL with the selected scope and permissions.

Select Copy beside the URL that was generated for you, paste it into your browser, and select your guild from the dropdown options:

Creating-a-Discord-select-your-grid

Click Authorize, and you’re done!

 

Authorized
If you go back to your guild, then you’ll see that the bot has been added:

Bot added

In summary, you’ve created:

  • An application that your bot will use to authenticate with Discord’s APIs
  • A bot user that you’ll use to interact with other users and events in your guild
  • A guild in which your user account and your bot user will be active
  • ADiscordaccount with which you created everything else and that you’ll use to interact with your bot

Now, you know how to make a Discord bot using the Developer Portal. Next comes the fun stuff: implementing your bot in Python!

How to Make a Discord Bot in Python

Since you’re learning how to make a Discord bot with Python, you’ll be using discord.py.

discord.py is a Python library that exhaustively implements Discord’s APIs in an efficient and Pythonic way. This includes utilizing Python’s implementation of Async IO

Begin by installing discord.py with pip:

$ pip install -U discord.py

Now that you’ve installed discord.py, you’ll use it to create your first connection to Discord!

Creating a Discord Connection

The first step in implementing your bot user is to create a connection to Discord. With discord.py, you do this by creating an instance of Client:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')

client.run(TOKEN)

A Client is an object that represents a connection to Discord. A Client handles events, tracks state, and generally interacts with Discord APIs.

Here, you’ve created a Client and implemented its on_ready() event handler, which handles the event when the Client has established a connection to Discord and it has finished preparing the data that Discord has sent, such as login state, guild and channel data, and more.

In other words, on_ready() will be called (and your message will be printed) once client is ready for further action. You’ll learn more about event handlers later in this article.

When you’re working with secrets such as your Discord token, it’s good practice to read it into your program from an environment variable. Using environment variables helps you:

  • Avoid putting the secrets into source control
  • Use different variables for development and production environments without changing your code

While you could export DISCORD_TOKEN={your-bot-token}, an easier solution is to save a .env file on all machines that will be running this code. This is not only easier, since you won’t have to export your token every time you clear your shell, but it also protects you from storing your secrets in your shell’s history.

Create a file named .env in the same directory as bot.py:

You’ll need to replace {your-bot-token} with your bot’s token, which you can get by going back to the Bot page on the Developer portal and clicking Copy under the TOKEN section:

 Creating-a-Discord-adding-bot-token

Looking back at the bot.py code, you’ll notice a library called dotnev. This library is handy for working with .env files. load_dotenv()loads environment variables from a .env file into your shell’s environment variables so that you can use them in your code.

Install dotenv with pip:

pip install -U python-dotenv

Finally, client.run() runs your Client using your bot’s token.

Now that you’ve set up both bot.py and .env, you can run your code:

python bot.py
Shikhaboat#5531 has connected to Discord!

Great! Your Client has connected to Discord using your bot’s token. In the next section, you’ll build on this Client by interacting with more Discord APIs.

Interacting With Discord APIs

Using a Client, you have access to a wide range of Discord APIs.

For example, let’s say you wanted to write the name and identifier of the guild that you registered your bot user with to the console.

First, you’ll need to add a new environment variable:

# .env
DISCORD_TOKEN={your-bot-token}
DISCORD_GUILD={your-guild-name}

Don’t forget that you’ll need to replace the two placeholders with actual values:

  1. {your-bot-token}
  2. {your-guild-name}

Remember that Discord calls on_ready(), which you used before, once the Client has made the connection and prepared the data. So, you can rely on the guild data being available inside on_ready():

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

client.run(TOKEN)

Here, you looped through the guild data that Discord has sent client, namely client.guilds. Then, you found the guild with the matching name and printed a formatted string to stdout.

Run the program to see the results:

 python bot.py
Shikhaboat#5531 is connected to the following guild:
Shikhaboat#5531(id: 571759877328732195)

Great! You can see the name of your bot, the name of your server, and the server’s identification number.

Another interesting bit of data you can pull from a guild is the list of users who are members of the guild:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})\n'
    )

    members = '\n - '.join([member.name for member in guild.members])
    print(f'Guild Members:\n - {members}')

client.run(TOKEN)

By looping through guild.members, you pulled the names of all of the members of the guild and printed them with a formatted string.

When you run the program, you should see at least the name of the account you created the guild with and the name of the bot user itself:

$ python bot.py
Shikhaboat#5531 is connected to the following guild:
Shikhaboat#5531(id: 571759877328732195)
Guild Members:
 - aronq2
 - RealPythonTutorialBot

These examples barely scratch the surface of the APIs available on Discord, be sure to check out their documentation to see all that they have to offer.

Next, you’ll learn about some utility functions and how they can simplify these examples.

Using Utility Functions

Let’s take another look at the example from the last section where you printed the name and identifier of the bot’s guild:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

client.run(TOKEN)

You could clean up this code by using some of the utility functions available in discord.py.

discord.utils.find is one utility that can improve the simplicity and readability of this code by replacing the for loop with an intuitive, abstracted function:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    guild = discord.utils.find(lambda g: g.name == GUILD, client.guilds)
    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

client.run(TOKEN)

<find() takes a function, called a predicate, which identifies some characteristic of the element in the iterable that you’re looking for. Here, you used a particular type of anonymous function, called a lambda, as the predicate.

In this case, you’re trying to find the guild with the same name as the one you stored in the DISCORD_GUILD environment variable. Once find() locates an element in the iterable that satisfies the predicate, it will return the element. This is essentially equivalent to the break statement in the previous example, but cleaner.

discord.py has even abstracted this concept one step further with the get.utility():

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    guild = discord.utils.get(client.guilds, name=GUILD)
    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

client.run(TOKEN)

get() takes the iterable and some keyword arguments. The keyword arguments represent attributes of the elements in the iterable that must all be satisfied for get() to return the element.

In this example, you’ve identified name=GUILD as the attribute that must be satisfied.

Now that you’ve learned the basics of interacting with APIs, you’ll dive a little deeper into the function that you’ve been using to access them: on_ready().

Responding to Events

You already learned that on_ready() is an event. In fact, you might have noticed that it is identified as such in the code by the client.event decorator.

But what is an event?

An event is something that happens on Discord that you can use to trigger a reaction in your code. Your code will listen for and then respond to events.

Using the example you’ve seen already, the on_ready() event handler handles the event that the Client has made a connection to Discord and prepared its response data.

So, when Discord fires an event, discord.py will route the event data to the corresponding event handler on your connected Client.

There are two ways in discord.py to implement an event handler:

  1. Using the client.event decorator
  2. Creating a subclass of Client and overriding its handler methods

You already saw the implementation using the decorator. Next, take a look at how to subclass Client:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

class CustomClient(discord.Client):
    async def on_ready(self):
        print(f'{self.user} has connected to Discord!')

client = CustomClient()
client.run(TOKEN)

Here, just like before, you’ve created a client variable and called <.run() with your Discord token. The actual Client is different, however. Instead of using the normal base class, client is an instance of CustomClient, which has an overridden on_ready() function.

There is no difference between the two implementation styles of events, but this tutorial will primarily use the decorator version because it looks similar to how you implement Bot commands, which is a topic you’ll cover in a bit.

Welcoming New Members

Previously, you saw the example of responding to the event where a member joins a guild. In that example, your bot user could send them a message, welcoming them to your Discord community.

Now, you’ll implement that behavior in your Client, using event handlers, and verify its behavior in Discord:

# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user.name} has connected to Discord!')

@client.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(
        f'Hi {member.name}, welcome to my Discord server!'
    )

client.run(TOKEN)

Like before, you handled the on_ready() event by printing the bot user’s name in a formatted string. New, however, is the implementation of the on_member_join() event handler.

on_member_join(), as its name suggests, handles the event of a new member joining a guild.

In this example, you used member.create_dm()to create a direct message channel. Then, you used that channel to send() a direct message to that new member.

Now, let’s test out your bot’s new behavior.

First, run your new version of bot.py and wait for the on_ready() event to fire, logging your message to stdout:

$ python bot.py
ShikhaBot has connected to Discord!

Now, head over to Discord, log in, and navigate to your guild by selecting it from the left-hand side of the screen:

Creating-a-Discord-navigate-to-server

Select Invite People just beside the guild list where you selected your guild. Check the box that says Set this link to never expire and copy the link:

InvitePepole

Now, with the invite link copied, create a new account and join the guild using your invite link.

First, you’ll see that Discord introduced you to the guild by default with an automated message. More importantly though, notice the badge on the left-hand side of the screen that notifies you of a new message:

 Creating-a-Discord-account-new-message.
When you select it, you’ll see a private message from your bot user:

 Boat-is-created

Perfect! Your bot user is now interacting with other users with minimal code.

Conclusion

Congratulations! Now, you’ve learned how to make a Discord bot in Python. You’re able to build bots for interacting with users in guilds that you create or even bots that other users can invite to interact with their communities.

 

Pthread_detach example – POSIX: Detached vs Joinable threads | pthread_join() & pthread_detach() Examples

POSIX- Detached vs Joinable threads, pthread_join() & pthread_detach() Examples

Pthread_detach example: Guys who are looking for the perfect guide or tutorial for POSIX: Detached vs Joinable threads and pthread_join() & pthread_detach() examples? Can stay with us. This tutorial will explain & give you complete guidance while programming by using these Detached & Joinable Threads. Before going to learn Detached vs Joinable threads along with pthread_join() & pthread_detach() examples let’s start understanding what is thread and pthread?

About threads

Pthread_join examples: A thread is a semi-process that has its own stack and executes a given piece of code. threads within the same process run in shared memory space, it defined as an independent stream of instructions that can be scheduled to run as such by the operating system.

What is pthreads?

Pthread_detach: POSIX Threads usually referred to as pthreads, is an execution model that exists independently from a language, as well as a parallel execution model. It allows a program to control multiple different flows of work that overlap in time.

Thread can be run in two modes. They are as such,

1. Joinable mode
2. Detached mode

Joinable Thread & pthread_join()

Pthread_join example: A joinable thread will not release any resource even after the end of the thread function until some other thread calls pthread_join() with its ID.

Whereas pthread_join() is a blocking call, it will block the calling thread until the other thread ends.

We will pass two parameters in pthread-

1. The ID of the target thread

2. Address of (void *) i.e. (void **), it will point to the return value of thread function i.e. pointer to (void *).

pthread_join() will return non-zero value in case of error.

Example of pthread_join()

Pthread_join(): Below is the example for joinable thread,

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
void * threadFunc(void * arg)
{
    std::cout << "Thread Function :: Start" << std::endl;
    // Sleep for 2 seconds
    sleep(2);
    std::cout << "Thread Function :: End" << std::endl;
    // Return value from thread
    return new int(6);
}
int main()
{
    // Thread id
    pthread_t threadId;
    // Create a thread that will funtion threadFunc()
    int err = pthread_create(&threadId, NULL, &threadFunc, NULL);
    // Check if thread is created sucessfuly
    if (err)
    {
        std::cout << "Thread creation failed : " << strerror(err);
        return err;
    }
    else
        std::cout << "Thread Created with ID : " << threadId << std::endl;
    // Do some stuff
    void * ptr = NULL;
    std::cout << "Waiting for thread to exit" << std::endl;
    // Wait for thread to exit
    err = pthread_join(threadId, &ptr);
    if (err)
    {
        std::cout << "Failed to join Thread : " << strerror(err) << std::endl;
        return err;
    }
    if (ptr)
        std::cout << " value returned by thread : " << *(int *) ptr
                << std::endl;
    delete (int *) ptr;
    return 0;
}

Output:

Thread Created with ID : 1407020804273336
Waiting for thread to exit
Thread Function :: Start
Thread Function :: End
value returned by thread : 6

Also Check:

Detached Thread & pthread_detach()

Pthread_detach: By default all threads are joinable, we will call pthread_detach() so to make a thread detached. A Detached thread automatically releases its allocated resources on exit. No other thread needs to join it.

#include <pthread.h>

int pthread_detach(pthread_t thread);

There is no way to determine its return value of the detached thread function.
pthread_detach() will return non zero value in case of error.

Output can change on your system because both the main and thread functions are running in parallel.

If the main function exits then all other threads will be exited.

pthread_detach() Example

Below is the example,

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
void * threadFunc(void * arg)
{
    std::cout << "Thread Function :: Start" << std::endl;
    std::cout << "Thread Function :: End" << std::endl;
    // Return value from thread
    return NULL;
}
int main()
{
    // Thread id
    pthread_t threadId;
    // Create a thread that will funtion threadFunc()
    int err = pthread_create(&threadId, NULL, &threadFunc, NULL);
    // Check if thread is created sucessfuly
    if (err)
    {
        std::cout << "Thread creation failed : " << strerror(err);
        return err;
    }
    else
        std::cout << "Thread Created with ID : " << threadId << std::endl;
    // Do some stuff
    err = pthread_detach(threadId);
    if (err)
        std::cout << "Failed to detach Thread : " << strerror(err) << std::endl;
    // Sleep for 2 seconds because if main function exits, then other threads will
    // be also be killed. Sleep for 2 seconds, so that detached exits by then
    sleep(2);
    std::cout << "Main function ends " << std::endl;
    return 0;
}

Output:

Thread Created with ID : 139703273027328
Thread Function :: Start
Thread Function :: End
Main function ends

Python – Ways to remove duplicates from list

Remove duplicates from list python: List is an important container and used almost in every code of day-day programming as well as web-development, more it is used, more is the requirement to master it and hence knowledge of its operations is necessary. This article focuses on one of the operations of getting the unique list from a list that contains a possible duplicated. Remove duplicates from list operation has large number of applications and hence, its knowledge is good to have.

How to Remove Duplicates From a Python List

Method 1 : Naive method

In Naive method, we simply traverse the list and append the first occurrence of the element in new list and ignore all the other occurrences of that particular element.

# Using Naive methods:

Using Naive method

Output :

Remove duplicates from list using Naive method output

Method 2 : Using list comprehension

List comprehensions are Python functions that are used for creating new sequences (such as lists, tuple, etc.) using previously created sequence. This makes code more efficient and easy to understand. This method has working similar to the above method, but this is just a one-liner shorthand of longer method done with the help of list comprehension.

# Using list comprehension

Remove duplicates from list using list comprehension
Output :

Remove duplicates from list using list comprehension output

Method 3 : Using set():

We can remove duplicates from a list using an inbuilt function called set(). The set() always return distinct elements. Therefore, we use the set() for removing duplicates.But the main and notable drawback of this approach is that the ordering of the element is lost in this particular method.

# Using set()

Remove duplicates from list using set method
Output :

Remove duplicates from list using set method output

Method 4 : Using list comprehension + enumerate():

Enumerate can also be used for removing duplicates when used with the list comprehension.It basically looks for already occurred elements and skips adding them. It preserves the list ordering.

# Using list comprehension + enumerate()

Using list comprehension + enumerate()
Output :

Using list comprehension + enumerate() output
Method 5 : Using collections.OrderedDict.fromkeys():

This is fastest method to achieve the particular task. It first removes the duplicates and returns a dictionary which has to be converted to list. This works well in case of strings also.

# Using collections.OrderedDict.fromkeys()

Using collections.OrderedDict.fromkeys()
Output :

Using collections.OrderedDict.fromkeys() output

Conclusion :

In conclusion, nowyou may know “how to remove duplicates from a list in python?“. There are different ways but the using collections.OrderedDict.fromkeys() method is the best in accordance with the programming efficiency of the computer.

Python: Add column to dataframe in Pandas ( based on other column or list or default value)

Python-Add column to dataframe in Pandas

Pandas add a column: In this tutorial, we are going to discuss different ways to add columns to the dataframe in pandas. Moreover, you can have an idea about the Pandas Add Column, Adding a new column to the existing DataFrame in Pandas and many more from the below explained various methods.

Pandas Add Column

Pandas is one such data analytics library created explicitly for Python to implement data manipulation and data analysis. The Pandas library made of specific data structures and operations to deal with numerical tables, analyzing data, and work with time series.

Basically, there are three ways to add columns to pandas i.e., Using [] operator, using assign() function & using insert().

We will discuss it all one by one.

First, let’s create a dataframe object,

import pandas as pd
# List of Tuples
students = [('Rakesh', 34, 'Agra', 'India'),
            ('Rekha', 30, 'Pune', 'India'),
            ('Suhail', 31, 'Mumbai', 'India'),
            ('Neelam', 32, 'Bangalore', 'India'),
            ('Jay', 16, 'Bengal', 'India'),
            ('Mahak', 17, 'Varanasi', 'India')]
# Create a DataFrame object
df_obj = pd.DataFrame(students,
                      columns=['Name', 'Age', 'City', 'Country'],
                      index=['a', 'b', 'c', 'd', 'e', 'f'])
print(df_obj )

Output:

    Name    Age  City        Country
a  Rakesh  34     Agra        India
b  Rekha   30     Pune        India
c  Suhail    31    Mumbai   India
d  Neelam 32   Bangalore India
e  Jay         16   Bengal      India
f  Mahak    17  Varanasi     India

Do Check:

Add column to dataframe in pandas using [] operator

import pandas as pd
# List of Tuples
students = [('Rakesh', 34, 'Agra', 'India'),
            ('Rekha', 30, 'Pune', 'India'),
            ('Suhail', 31, 'Mumbai', 'India'),
            ('Neelam', 32, 'Bangalore', 'India'),
            ('Jay', 16, 'Bengal', 'India'),
            ('Mahak', 17, 'Varanasi', 'India')]
# Create a DataFrame object
df_obj = pd.DataFrame(students,
                      columns=['Name', 'Age', 'City', 'Country'],
                      index=['a', 'b', 'c', 'd', 'e', 'f'])

# Add column with Name Score
df_obj['Score'] = [10, 20, 45, 33, 22, 11]
print(df_obj )

Output:

      Name     Age   City        Country   Score
a    Rakesh    34    Agra          India      10
b    Rekha     30    Pune          India      20
c    Suhail     31     Mumbai    India      45
d    Neelam  32    Bangalore  India      33
e    Jay         16     Bengal       India      22
f    Mahak    17    Varanasi     India       11

So in the above example, you have seen we have added one extra column ‘score’ in our dataframe. So in this, we add a new column to Dataframe with Values in the list. In the above dataframe, there is no column name ‘score’ that’s why it added if there is any column with the same name that already exists then it will replace all its values.

Add new column to DataFrame with same default value

import pandas as pd
# List of Tuples
students = [('Rakesh', 34, 'Agra', 'India'),
            ('Rekha', 30, 'Pune', 'India'),
            ('Suhail', 31, 'Mumbai', 'India'),
            ('Neelam', 32, 'Bangalore', 'India'),
            ('Jay', 16, 'Bengal', 'India'),
            ('Mahak', 17, 'Varanasi', 'India')]
# Create a DataFrame object
df_obj = pd.DataFrame(students,
                      columns=['Name', 'Age', 'City', 'Country'],
                      index=['a', 'b', 'c', 'd', 'e', 'f'])

df_obj['Total'] = 100
print(df_obj)

Output:

         Name    Age    City     Country      Total
a       Rakesh   34    Agra       India          100
b       Rekha    30    Pune       India          100
c       Suhail     31   Mumbai  India          100
d       Neelam  32  Bangalore India        100
e       Jay          16  Bengal       India        100
f       Mahak     17 Varanasi     India        100

So in the above example, we have added a new column ‘Total’ with the same value of 100 in each index.

Add column based on another column

Let’s add a new column ‘Percentage‘ where entrance at each index will be added by the values in other columns at that index i.e.,

df_obj['Percentage'] = (df_obj['Marks'] / df_obj['Total']) * 100
df_obj

Output:

    Name  Age       City    Country  Marks  Total  Percentage
a   jack   34     Sydeny  Australia     10     50        20.0
b   Riti   30      Delhi      India     20     50        40.0
c  Vikas   31     Mumbai      India     45     50        90.0
d  Neelu   32  Bangalore      India     33     50        66.0
e   John   16   New York         US     22     50        44.0
f   Mike   17  las vegas         US     11     50        22.0

Append column to dataFrame using assign() function

So for this, we are going to use the same dataframe which we have created in starting.

Syntax:

DataFrame.assign(**kwargs)

Let’s add columns in DataFrame using assign().

import pandas as pd
# List of Tuples
students = [('Rakesh', 34, 'Agra', 'India'),
            ('Rekha', 30, 'Pune', 'India'),
            ('Suhail', 31, 'Mumbai', 'India'),
            ('Neelam', 32, 'Bangalore', 'India'),
            ('Jay', 16, 'Bengal', 'India'),
            ('Mahak', 17, 'Varanasi', 'India')]
# Create a DataFrame object
df_obj = pd.DataFrame(students,
                      columns=['Name', 'Age', 'City', 'Country'],
                      index=['a', 'b', 'c', 'd', 'e', 'f'])
mod_fd = df_obj.assign(Marks=[10, 20, 45, 33, 22, 11])
print(mod_fd)

Output:

Add-a-column-using-assign

It will return a new dataframe with a new column ‘Marks’ in that Dataframe. Values provided in the list will be used as column values.

Add column in DataFrame based on other column using lambda function

In this method using two existing columns i.e, score and total value we are going to create a new column i.e..’ percentage’.

import pandas as pd
# List of Tuples
students = [('Rakesh', 34, 'Agra', 'India'),
            ('Rekha', 30, 'Pune', 'India'),
            ('Suhail', 31, 'Mumbai', 'India'),
            ('Neelam', 32, 'Bangalore', 'India'),
            ('Jay', 16, 'Bengal', 'India'),
            ('Mahak', 17, 'Varanasi', 'India')]
# Create a DataFrame object
df_obj = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Country'],
                      index=['a', 'b', 'c', 'd', 'e', 'f'])
df_obj['Score'] = [10, 20, 45, 33, 22, 11]
df_obj['Total'] = 100
df_obj = df_obj.assign(Percentage=lambda x: (x['Score'] / x['Total']) * 100)
print(df_obj)

Output:

Add-column-based-on-another-column

Add new column to Dataframe using insert()

import pandas as pd
# List of Tuples
students = [('Rakesh', 34, 'Agra', 'India'),
            ('Rekha', 30, 'Pune', 'India'),
            ('Suhail', 31, 'Mumbai', 'India'),
            ('Neelam', 32, 'Bangalore', 'India'),
            ('Jay', 16, 'Bengal', 'India'),
            ('Mahak', 17, 'Varanasi', 'India')]
# Create a DataFrame object
df_obj = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Country'],
                      index=['a', 'b', 'c', 'd', 'e', 'f'])
# Insert column at the 2nd position of Dataframe
df_obj.insert(2, "Marks", [10, 20, 45, 33, 22, 11], True)
print(df_obj)

Output:

add-a-column-using-insert

 

In other examples, we have added a new column at the end of the dataframe, but in the above example, we insert a new column in between the other columns of the dataframe, then we can use the insert() function.

Add a column to Dataframe by dictionary

import pandas as pd
# List of Tuples
students = [('Rakesh', 34, 'Agra', 'India'),
            ('Rekha', 30, 'Pune', 'India'),
            ('Suhail', 31, 'Mumbai', 'India'),
            ('Neelam', 32, 'Bangalore', 'India'),
            ('Jay', 16, 'Bengal', 'India'),
            ('Mahak', 17, 'Varanasi', 'India')]
# Create a DataFrame object
df_obj = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Country'],
                      index=['a', 'b', 'c', 'd', 'e', 'f'])
ids = [11, 12, 13, 14, 15, 16]
# Provide 'ID' as the column name and for values provide dictionary
df_obj['ID'] = dict(zip(ids, df_obj['Name']))
print(df_obj)

Output:

Add-a-column-using-dictionary

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

Read more Articles on Python Data Analysis Using Padas – Add Contents to a Dataframe