Create an account


Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Search Forums

(Advanced Search)

Forum Statistics
» Members: 20,102
» Latest member: finley52
» Forum threads: 21,740
» Forum posts: 22,603

Full Statistics

Online Users
There are currently 518 online users.
» 0 Member(s) | 513 Guest(s)
Applebot, Baidu, Bing, Google, Yandex

 
  PC - Mr. Sun's Hatbox
Posted by: xSicKxBot - 05-04-2023, 07:03 AM - Forum: New Game Releases - No Replies

Mr. Sun's Hatbox



Mr Sun’s Hatbox is a slapstick, roguelite platformer about getting the job done at all costs. Upgrade your HQ, your team, and your tools so you can take on increasingly dangerous (and ridiculous) missions, wearing hats with amazing (or questionable) potential.

Publisher: Kenny Sun

Release Date: Apr 20, 2023




https://www.metacritic.com/game/pc/mr-suns-hatbox

Print this item

  [Tut] How I Designed a Personal Portfolio Website with Django (Part 2)
Posted by: xSicKxBot - 05-03-2023, 12:30 PM - Forum: Python - No Replies

How I Designed a Personal Portfolio Website with Django (Part 2)

5/5 – (1 vote)

We are designing a personal portfolio website using the Django web framework.

In the first part of this series, we learned how to create Django models for our database. We created an admin panel, and added ourselves as a superuser. I expect that by now you have used the admin panel to add your sample projects.

You are required to go through the first part of this series for you to follow along with us if you haven’t already done so. In this series, we will create a view function using the sample projects. By the end of this series, we will have created a fully functioning personal portfolio website.

The View Function



We can choose to use class-based views or function-based views, or both to create our portfolio website.

If you use class-based views, you must subclass it with Django’s ListView class to list all your sample projects. For a full sample project description, you must create another class and subclass it with Django’s DetailView class.

For our portfolio website, we will use function-based views so that you can learn how to query our database. Open the views.py file and write the following code:

from django.shortcuts import render
from .models import Project # Create your views here. def project_list(request): projects = Project.objects.all() context = { 'projects': projects } return render(request, 'index.html', context)

We import the Projects class and perform a query to retrieve all the objects in the table. This is a simple example of querying a database.

The context dictionary that contains the object is sent to the template file using the render() function. The function also renders the template, index.html. This tells us that all information available in the context dictionary will be displayed in the given template file.

This view function will only list all our sample projects. For a full description of the projects, we will have to create another view function.

def full_view(request, pk): project = Project.objects.get(pk=pk) context = { 'project': project } return render(request, 'full_view.html', context)

This view function looks similar to the previous one only that it comes with another parameter, pk. We perform another query to get an object based on its primary key. I will soon explain what is meant by primary key.

Template Files



We have to create two template files for our view functions. Then, a base.html file with Bootstrap added to make it look nice. The template files will inherit everything in the base.html file. Copy the following code and save it inside the templates folder as base.html.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container"> <a class="navbar-brand" href="{% url 'index' %}">Personal Portfolio</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'index' %}">Home</a> </li> </ul> </div> </div> </nav> <div class="container"> {% block content %}{% endblock %}
</div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

The a tag has a {% ... %} tag in its href attribute. This is Django’s way of linking to the index.html file. The block content and endblock tags inside the div tag is reserved for any template file inheriting from the base.html file.

As we will see, any template file inheriting from the base.html file must include such tags.

The Bootstrap files are beyond the scope of this article. Check the documentation to learn more.

Create the index.html file inside the template folder as indicated in the view function. Then, write the following script:

{% extends "base.html" %}
{% load static %}
{% block content %}
<h1>Projects Completed</h1>
<div class="row">
{% for project in projects %} <div class="col-md-4"> <div class="card mb-2"> <img class="card-img-top" src="{{ project.image.url }}"> <div class="card-body"> <h5 class="card-title">{{ project.title }}</h5> <p class="card-text">{{ project.description }}</p> <a href="{% url 'full_view' project.pk %}" class="btn btn-primary"> Read More </a> </div> </div> </div> {% endfor %}
</div>
{% endblock %}

The index.html file inherits the base.html as shown in the first line of the code. Imagine all the scripts we have to write to render hundreds or even thousands of sample projects! Once again, Django comes to the rescue with its template engine, for loops.


Using the for loop, we loop through all the projects (no matter how many they are) passed by the context dictionary. Each iteration renders the image (using the img tag), the title, the description and a link to get the full description of the project.

Notice that the a tag is pointing to a given project represented as project.pk. This is the primary key passed as a parameter in the second view function. More on that soon.

Again, notice the block content and the endblock tags. Since the index.html extends the base.html file, it will only display all that is found in the file. Any addition must be written inside the block content and endblock tags. Otherwise, it won’t be displayed.

Finally, the full_view.html file:

{% extends "base.html" %}
{% load static %}
{% block content %}
<h1>{{ project.title }}</h1>
<div class="row"> <div class="col-md-8"> <img src="{% project.image.url %}" alt="" width="100%"> </div> <div class="col-md-4"> <h5>About the project:</h5> <p>{{ project.description }}</p> <br> <h5>Technology used:</h5> <p>{{ project.technology }}</p> </div>
</div>
{% endblock %}

That’s all about our template files. Notice how everything is linked to our database model as we learned in the first part of this series. We retrieve data from the database, pass them to the view function, and render them in the template files.


We haven’t let Django know of an existing templates folder. Go to the settings.py file, under the TEMPLATES section. Register the templates folder there.

TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], #add these 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },
]

Registering the URLs



We need to hook up our view functions to URLs. First is the project-level URL. Open the urls.py in the project folder, and add these:

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('portfolio.urls')),
] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

We register the file using the include() method. So, once we start the local server, and go to http://127.0.0.1:8000, we will see our home page which is the index.html file. Then, in the if statement, we tell Django where to find the user-uploaded images.

Next are the app-level URLs. Create a urls.py file in the portfolio folder.

from django.urls import path
from .views import project_list, full_view urlpatterns = [ path('', project_list, name='index'), path('<int:pk>/', full_view, name='full_view'),
]

The full_view URL is hooked up with a primary key. It is the same primary key in the templates file and in the second view function. This is an integer representing the number of each project. For the first project you added in the previous series, the URL will be http://127.0.0.1:8000/1

Hoping that everything is set, start the local server, and you will see everything displayed.

Conclusion


We have successfully come to the end of the second series of this project. The first series is here:

? First Part: How I Designed a Personal Portfolio Website with Django

If you encounter errors, be sure to check the full code on my GitHub page. Our app is now running in the local server. In the final series of this project, we will see how we can deploy this to a production server.



https://www.sickgaming.net/blog/2023/05/...go-part-2/

Print this item

  PC - Rusted Moss
Posted by: xSicKxBot - 05-03-2023, 12:30 PM - Forum: New Game Releases - No Replies

Rusted Moss



Humanity is on the brink of collapse and will soon be invaded by faeries. In a desperate bid to survive, humans have empowered their own witches with stolen fae magic.

But all is not lost, as the humans were deceived - for one of their own is not what she seems. The fae have stolen a human baby, and replaced it with something else...

Raised by unsuspecting human parents, Fern is a changeling whose true loyalties have emerged. Alongside a mysterious shadow named Puck, she sets off on a journey to return fae to the world and end the Age of Men.

Whose side will you choose - human or fae?

Rusted Moss is a twin-stick shooter metroidvania where you sling around the map with your grapple, blasting your way through witches and rusted machine monstrosities alike.

Publisher: Playism

Release Date: Apr 23, 2023




https://www.metacritic.com/game/pc/rusted-moss

Print this item

  [Tut] Python Converting List of Strings to * [Ultimate Guide]
Posted by: xSicKxBot - 05-02-2023, 01:17 PM - Forum: Python - No Replies

Python Converting List of Strings to * [Ultimate Guide]

5/5 – (1 vote)

Since I frequently handle textual data with Python ?, I’ve encountered the challenge of converting lists of strings into different data types time and again. This article, originally penned for my own reference, decisively tackles this issue and might just prove useful for you too!

Let’s get started! ?

Python Convert List of Strings to Ints



This section is for you if you have a list of strings representing numbers and want to convert them to integers.

The first approach is using a for loop to iterate through the list and convert each string to an integer using the int() function.

Here’s a code snippet to help you understand:

string_list = ['1', '2', '3']
int_list = [] for item in string_list: int_list.append(int(item)) print(int_list) # Output: [1, 2, 3]

Another popular method is using list comprehension. It’s a more concise way of achieving the same result as the for loop method.

Here’s an example:

string_list = ['1', '2', '3']
int_list = [int(item) for item in string_list]
print(int_list) # Output: [1, 2, 3]

You can also use the built-in map() function, which applies a specified function (in this case, int()) to each item in the input list. Just make sure to convert the result back to a list using list().

Take a look at this example:

string_list = ['1', '2', '3']
int_list = list(map(int, string_list))
print(int_list) # Output: [1, 2, 3]

For a full guide on the matter, check out our blog tutorial:

? Recommended: How to Convert a String List to an Integer List in Python

Python Convert List Of Strings To Floats



If you want to convert a list of strings to floats in Python, you’ve come to the right place. Next, let’s explore a few different ways you can achieve this. ?

First, one simple and Pythonic way to convert a list of strings to a list of floats is by using list comprehension.

Here’s how you can do it:

strings = ["1.2", "2.3", "3.4"]
floats = [float(x) for x in strings]

In this example, the list comprehension iterates over each element in the strings list, converting each element to a float using the built-in float() function. ?

Another approach is to use the map() function along with float() to achieve the same result:

strings = ["1.2", "2.3", "3.4"]
floats = list(map(float, strings))

The map() function applies the float() function to each element in the strings list, and then we convert the result back to a list using the list() function. ?

If your strings contain decimal separators other than the dot (.), like a comma (,), you need to replace them first before converting to floats:

strings = ["1,2", "2,3", "3,4"]
floats = [float(x.replace(',', '.')) for x in strings]

This will ensure that the values are correctly converted to float numbers. ?

? Recommended: How to Convert a String List to a Float List in Python

Python Convert List Of Strings To String


You might need to convert a list of strings into a single string in Python. ? It’s quite simple! You can use the join() method to combine the elements of your list.

Here’s a quick example:

string_list = ['hello', 'world']
result = ''.join(string_list) # Output: 'helloworld'

You might want to separate the elements with a specific character or pattern, like spaces or commas. Just modify the string used in the join() method:

result_with_spaces = ' '.join(string_list) # Output: 'hello world'
result_with_commas = ', '.join(string_list) # Output: 'hello, world'

If your list contains non-string elements such as integers or floats, you’ll need to convert them to strings first using a list comprehension or a map() function:

integer_list = [1, 2, 3] # Using list comprehension
str_list = [str(x) for x in integer_list]
result = ','.join(str_list) # Output: '1,2,3' # Using map function
str_list = map(str, integer_list)
result = ','.join(str_list) # Output: '1,2,3'

Play around with different separators and methods to find the best suits your needs.

Python Convert List Of Strings To One String



Are you looking for a simple way to convert a list of strings to a single string in Python?

The easiest method to combine a list of strings into one string uses the join() method. Just pass the list of strings as an argument to join(), and it’ll do the magic for you.

Here’s an example:

list_of_strings = ["John", "Charles", "Smith"]
combined_string = " ".join(list_of_strings)
print(combined_string)

Output:

John Charles Smith

You can also change the separator by modifying the string before the join() call. Now let’s say your list has a mix of data types, like integers and strings. No problem! Use the map() function along with join() to handle this situation:

list_of_strings = ["John", 42, "Smith"]
combined_string = " ".join(map(str, list_of_strings))
print(combined_string)

Output:

John 42 Smith

In this case, the map() function converts every element in the list to a string before joining them.

Another solution is using the str.format() method to merge the list elements. This is especially handy when you want to follow a specific template.

For example:

list_of_strings = ["John", "Charles", "Smith"]
result = " {} {} {}".format(*list_of_strings)
print(result)

Output:

John Charles Smith

And that’s it! ? Now you know multiple ways to convert a list of strings into one string in Python.

Python Convert List of Strings to Comma Separated String


So you’d like to convert a list of strings to a comma-separated string using Python.

Here’s a simple solution that uses the join() function:

string_list = ['apple', 'banana', 'cherry']
comma_separated_string = ','.join(string_list)
print(comma_separated_string)

This code would output:

apple,banana,cherry

Using the join() function is a fantastic and efficient way to concatenate strings in a list, adding your desired delimiter (in this case, a comma) between every element ?.

In case your list doesn’t only contain strings, don’t sweat! You can still convert it to a comma-separated string, even if it includes integers or other types. Just use list comprehension along with the str() function:

mixed_list = ['apple', 42, 'cherry']
comma_separated_string = ','.join(str(item) for item in mixed_list)
print(comma_separated_string)

And your output would look like:

apple,42,cherry

Now you have a versatile method to handle lists containing different types of elements ?


Remember, if your list includes strings containing commas, you might want to choose a different delimiter or use quotes to better differentiate between items.

For example:

list_with_commas = ['apple,green', 'banana,yellow', 'cherry,red']
comma_separated_string = '"{}"'.format('", "'.join(list_with_commas))
print(comma_separated_string)

Here’s the output you’d get:

"apple,green", "banana,yellow", "cherry,red"

With these tips and examples, you should be able to easily convert a list of strings (or mixed data types) to comma-separated strings in Python ?.

Python Convert List Of Strings To Lowercase


Let’s dive into converting a list of strings to lowercase in Python. In this section, you’ll learn three handy methods to achieve this. Don’t worry, they’re easy!

Solution: List Comprehension


Firstly, you can use list comprehension to create a list with all lowercase strings. This is a concise and efficient way to achieve your goal.

Here’s an example:

original_list = ["Hello", "WORLD", "PyThon"]
lowercase_list = [item.lower() for item in original_list]
print(lowercase_list) # Output: ['hello', 'world', 'python']

With this approach, the lower() method is applied to each item in the list, creating a new list with lowercase strings. ?

Solution: map() Function


Another way to convert a list of strings to lowercase is by using the map() function. This function applies a given function (in our case, str.lower()) to each item in a list.

Here’s an example:

original_list = ["Hello", "WORLD", "PyThon"]
lowercase_list = list(map(str.lower, original_list))
print(lowercase_list) # Output: ['hello', 'world', 'python']

Remember to wrap the map() function with the list() function to get your desired output. ?

Solution: For Loop


Lastly, you can use a simple for loop. This approach might be more familiar and readable to some, but it’s typically less efficient than the other methods mentioned.

Here’s an example:

original_list = ["Hello", "WORLD", "PyThon"]
lowercase_list = [] for item in original_list: lowercase_list.append(item.lower()) print(lowercase_list) # Output: ['hello', 'world', 'python']

I have written a complete guide on this on the Finxter blog. Check it out! ?

? Recommended: Python Convert String List to Lowercase

Python Convert List of Strings to Datetime



In this section, we’ll guide you through converting a list of strings to datetime objects in Python. It’s a common task when working with date-related data, and can be quite easy to achieve with the right tools!

So, let’s say you have a list of strings representing dates, and you want to convert this into a list of datetime objects. First, you’ll need to import the datetime module to access the essential functions. ?

from datetime import datetime

Next, you can use the strptime() function from the datetime module to convert each string in your list to a datetime object. To do this, simply iterate over the list of strings and apply the strptime function with the appropriate date format.

For example, if your list contained dates in the "YYYY-MM-DD" format, your code would look like this:

date_strings_list = ["2023-05-01", "2023-05-02", "2023-05-03"]
date_format = "%Y-%m-%d"
datetime_list = [datetime.strptime(date_string, date_format) for date_string in date_strings_list]

By using list comprehension, you’ve efficiently transformed your list of strings into a list of datetime objects! ?

Keep in mind that you’ll need to adjust the date_format variable according to the format of the dates in your list of strings. Here are some common date format codes you might need:

  • %Y: Year with century, as a decimal number (e.g., 2023)
  • %m: Month as a zero-padded decimal number (e.g., 05)
  • %d: Day of the month as a zero-padded decimal number (e.g., 01)
  • %H: Hour (24-hour clock) as a zero-padded decimal number (e.g., 17)
  • %M: Minute as a zero-padded decimal number (e.g., 43)
  • %S: Second as a zero-padded decimal number (e.g., 08)

Python Convert List Of Strings To Bytes


So you want to convert a list of strings to bytes in Python? No worries, I’ve got your back. ? This brief section will guide you through the process.

First things first, serialize your list of strings as a JSON string, and then convert it to bytes. You can easily do this using Python’s built-in json module.

Here’s a quick example:

import json your_list = ['hello', 'world']
list_str = json.dumps(your_list)
list_bytes = list_str.encode('utf-8')

Now, list_bytes is the byte representation of your original list. ?

But hey, what if you want to get back the original list from those bytes? Simple! Just do the reverse:

reconstructed_list = json.loads(list_bytes.decode('utf-8'))

And voilà! You’ve successfully converted a list of strings to bytes and back again in Python. ?

Remember that this method works well for lists containing strings. If your list includes other data types, you may need to convert them to strings first.

Python Convert List of Strings to Dictionary



Next, you’ll learn how to convert a list of strings to a dictionary. This can come in handy when you want to extract meaningful data from a list of key-value pairs represented as strings. ?

To get started, let’s say you have a list of strings that look like this:

data_list = ["Name: John", "Age: 30", "City: New York"]

You can convert this list into a dictionary using a simple loop and the split() method.

Here’s the recipe:

data_dict = {} for item in data_list: key, value = item.split(": ") data_dict[key] = value print(data_dict) # Output: {"Name": "John", "Age": "30", "City": "New York"}

Sweet, you just converted your list to a dictionary! ? But, what if you want to make it more concise? Python offers an elegant solution with dictionary comprehension.

Check this out:

data_dict = {item.split(": ")[0]: item.split(": ")[1] for item in data_list}
print(data_dict) # Output: {"Name": "John", "Age": "30", "City": "New York"}

With just one line of code, you achieved the same result. High five! ?

When dealing with more complex lists that contain strings in various formats or nested structures, it’s essential to use additional tools like the json.loads() method or the ast.literal_eval() function. But for simple cases like the example above, the loop and dictionary comprehension should be more than enough.

Python Convert List Of Strings To Bytes-Like Object


? How to convert a list of strings into a bytes-like object in Python? It’s quite simple and can be done easily using the json library and the utf-8 encoding.

Firstly, let’s tackle encoding your list of strings as a JSON string ?. You can use the json.dumps() function to achieve this.

Here’s an example:

import json your_list = ['hello', 'world']
json_string = json.dumps(your_list)

Now that you have the JSON string, you can convert it to a bytes-like object using the encode() method of the string ?.

Simply specify the encoding you’d like to use, which in this case is 'utf-8':

bytes_object = json_string.encode('utf-8')

And that’s it! Your list of strings has been successfully transformed into a bytes-like object. ? To recap, here’s the complete code snippet:

import json your_list = ['hello', 'world']
json_string = json.dumps(your_list)
bytes_object = json_string.encode('utf-8')

If you ever need to decode the bytes-like object back into a list of strings, just use the decode() method followed by the json.loads() function like so:

decoded_string = bytes_object.decode('utf-8')
original_list = json.loads(decoded_string)

Python Convert List Of Strings To Array



Converting a list of strings to an array in Python is a piece of cake ?.

One simple approach is using the NumPy library, which offers powerful tools for working with arrays. To start, make sure you have NumPy installed. Afterward, you can create an array using the numpy.array() function.

Like so:

import numpy as np string_list = ['apple', 'banana', 'cherry']
string_array = np.array(string_list)

Now your list is enjoying its new life as an array! ?

But sometimes, you may need to convert a list of strings into a specific data structure, like a NumPy character array. For this purpose, numpy.char.array() comes to the rescue:

char_array = np.char.array(string_list)

Now you have a character array! Easy as pie, right? ?

If you want to explore more options, check out the built-in split() method that lets you convert a string into a list, and subsequently into an array. This method is especially handy when you need to split a string based on a separator or a regular expression.

Python Convert List Of Strings To JSON


You’ve probably encountered a situation where you need to convert a list of strings to JSON format in Python. Don’t worry! We’ve got you covered. In this section, we’ll discuss a simple and efficient method to convert a list of strings to JSON using the json module in Python.

First things first, let’s import the necessary module:

import json

Now that you’ve imported the json module, you can use the json.dumps() function to convert your list of strings to a JSON string.

Here’s an example:

string_list = ["apple", "banana", "cherry"]
json_string = json.dumps(string_list)
print(json_string)

This will output the following JSON string:

["apple", "banana", "cherry"]

? Great job! You’ve successfully converted a list of strings to JSON. But what if your list contains strings that are already in JSON format?

In this case, you can use the json.loads() function:

string_list = ['{"name": "apple", "color": "red"}', '{"name": "banana", "color": "yellow"}']
json_list = [json.loads(string) for string in string_list]
print(json_list)

The output will be:

[{"name": "apple", "color": "red"}, {"name": "banana", "color": "yellow"}]

And that’s it! ? Now you know how to convert a list of strings to JSON in Python, whether it’s a simple list of strings or a list of strings already in JSON format.

Python Convert List Of Strings To Numpy Array



Are you looking to convert a list of strings to a numpy array in Python? Next, we will briefly discuss how to achieve this using NumPy.

First things first, you need to import numpy. If you don’t have it installed, simply run pip install numpy in your terminal or command prompt.

Once you’ve done that, you can import numpy in your Python script as follows:

import numpy as np

Now that numpy is imported, let’s say you have a list of strings with numbers that you want to convert to a numpy array, like this:

A = ['33.33', '33.33', '33.33', '33.37']

To convert this list of strings into a NumPy array, you can use a simple list comprehension to first convert the strings to floats and then use the numpy array() function to create the numpy array:

floats = [float(e) for e in A]
array_A = np.array(floats)

? Congratulations! You’ve successfully converted your list of strings to a numpy array! Now that you have your numpy array, you can perform various operations on it. Some common operations include:

  • Finding the mean, min, and max:
mean, min, max = np.mean(array_A), np.min(array_A), np.max(array_A)
  • Reshaping the array:
reshaped_array = array_A.reshape(2, 2)
array_B = np.array([1.0, 2.0, 3.0, 4.0])
result = array_A + array_B

Now you know how to convert a list of strings to a numpy array and perform various operations on it.

Python Convert List of Strings to Numbers


To convert a list of strings to numbers in Python, Python’s map function can be your best friend. It applies a given function to each item in an iterable. To convert a list of strings into a list of numbers, you can use map with either the int or float function.

Here’s an example: ?

string_list = ["1", "2", "3", "4", "5"]
numbers_int = list(map(int, string_list))
numbers_float = list(map(float, string_list))

Alternatively, using list comprehension is another great approach. Just loop through your list of strings and convert each element accordingly.✨

Here’s what it looks like:

numbers_int = [int(x) for x in string_list]
numbers_float = [float(x) for x in string_list]

Maybe you’re working with a list that contains a mix of strings representing integers and floats. In that case, you can implement a conditional list comprehension like this: ?

mixed_list = ["1", "2.5", "3", "4.2", "5"]
numbers_mixed = [int(x) if "." not in x else float(x) for x in mixed_list]

And that’s it! Now you know how to convert a list of strings to a list of numbers using Python, using different techniques like the map function and list comprehension.

Python Convert List Of Strings To Array Of Floats



? Starting out, you might have a list of strings containing numbers, like ['1.2', '3.4', '5.6'], and you want to convert these strings to an array of floats in Python.

Here’s how you can achieve this seamlessly:

Using List Comprehension


List comprehension is a concise way to create lists in Python. To convert the list of strings to a list of floats, you can use the following code:

list_of_strings = ['1.2', '3.4', '5.6']
list_of_floats = [float(x) for x in list_of_strings]

✨This will give you a new list list_of_floats containing [1.2, 3.4, 5.6].

Using numpy. ?


If you have numpy installed or are working with larger arrays, you might want to convert the list of strings to a numpy array of floats.

Here’s how you can do that:

import numpy as np list_of_strings = ['1.2', '3.4', '5.6']
numpy_array = np.array(list_of_strings, dtype=float)

Now you have a numpy array of floats: array([1.2, 3.4, 5.6]). ?

Converting Nested Lists


If you’re working with a nested list of strings representing numbers, like:

nested_list_of_strings = [['1.2', '3.4'], ['5.6', '7.8']]

You can use the following list comprehension:

nested_list_of_floats = [[float(x) for x in inner] for inner in nested_list_of_strings]

This will result in a nested list of floats like [[1.2, 3.4], [5.6, 7.8]]. ?


Pheww! Hope this article helped you solve your conversion problems. ?

Free Cheat Sheets! ?


If you want to keep learning Python and improving your skills, feel free to check out our Python cheat sheets (100% free): ?



https://www.sickgaming.net/blog/2023/05/...ate-guide/

Print this item

  (Indie Deal) FREE Echo of the Wilds, Koei Tecmo&Fatshark Sales
Posted by: xSicKxBot - 05-02-2023, 01:16 PM - Forum: Deals or Specials - No Replies

FREE Echo of the Wilds, Koei Tecmo&Fatshark Sales

Echo of the Wilds FREEbie
[freebies.indiegala.com]
Brave a new world in Stranded: Alien Dawn, a planet survival sim placing the fate of a small marooned group in your hands. Forge your story through compelling and immersive strategic gameplay as you make vital decisions to protect your survivors.
https://www.youtube.com/watch?v=47VAbXyk_l0&ab_channel=Stranded%3AAlienDawn
Koei Tecmo&Fatshark Sale
[www.indiegala.com]
Relive the dramatic political events of the 19th century in this first immersion pack for Victoria 3.
https://www.youtube.com/watch?v=ZZhUadmaP8M&ab_channel=ParadoxInteractive


https://steamcommunity.com/groups/indieg...0323333731

Print this item

  PC - Dead Island 2
Posted by: xSicKxBot - 05-02-2023, 01:16 PM - Forum: New Game Releases - No Replies

Dead Island 2



Dead Island 2 is stylish, vibrant and flooded with zombie infection. Explore iconic, gore-drenched Los Angeles. Meet larger-than-life characters. Slay countless foes in exquisitely bloody detail. And evolve to become the ultimate Zombie Slayer!

A deadly virus is spreading across Los Angeles, turning inhabitants into zombies. Bitten, infected, but more than just immune, uncover the truth behind the outbreak and discover who -or what- you are. Los Angeles is in quarantine and the military have retreated. Only you, and the handful of others who happen to be resistant to the pathogen, hold the future of the city (and humanity) in the balance.

Features:

Explore HELL-A – Dead Island 2 takes players across the most iconic locations of the City of Angels, now stained with horror, in an exciting pulp journey from the verdant suburbia of Beverly Hills to the quirky promenade of Venice Beach.

Brutal Melee Sandbox – Combat delivers the most intense, visceral and gory first person experience possible, with plenty of weapons and tactical (and brutal) options to chew your way through the zombie horde. Whether you’re slicing, smashing, burning or ripping, we want you to truly feel it.

Be the Ultimate Zombie Slayer – There are six characters to choose from, each with their own unique personality and dialogues. You can fully customize the abilities of each Slayer, with our brand-new skill system allowing you to re-spec instantly and try out the craziest builds.

Zombie Infestation – Ready to experience the most advanced dismemberment system in games? Our LA is crawling with zombies that look and react realistically. These mutated wretches are the reanimated, rotten heart of Dead Island 2 with dozens of distinct zombie types, each with their own mutations, attacks and hundreds of visual LA-themed variants. Our monsters are relentless, challenging, and true Los Angelinos. Will you be able to survive?

A Cinematic Co-op Adventure – As a proper RPG experience, Dead Island 2 offers plenty of exciting quests, a crazy cast of characters, and a thrilling pulp story, to truly immerse you in its twisted universe. Re-playability is guaranteed. Add an over-the-top co-op mode for up to three players, and you’ll stay in LA for a very long (and gory) trip.

Publisher: Deep Silver

Release Date: Apr 21, 2023




https://www.metacritic.com/game/pc/dead-island-2

Print this item

  (Indie Deal) Evil Dead is out on PC, IMGN Deals
Posted by: xSicKxBot - 05-01-2023, 07:07 PM - Forum: Deals or Specials - No Replies

Evil Dead is out on PC, IMGN Deals

Step into the shoes of Ash Williams or his friends from the iconic Evil Dead franchise in a game loaded with over-the-top co-op & PVP multiplayer action! Play as a team of 4 survivors in a game inspired by all 3 original Evil Dead films as well as the Ash vs Evil Dead television series.
https://www.youtube.com/watch?v=Wrg54GrpSEU&ab_channel=EvilDead%3ATheGame
Explore a dark and oneiric world of rampant nature and corrupted cities. Embody a tiny being of light on its path towards awakening. Fight your inner demons and restore your balance.
https://www.youtube.com/watch?v=O3WwG5Fl_o8&ab_channel=Embers
IMGN.PRO Sale, up to 90% OFF
[www.indiegala.com]
You find your world in danger once again, but this time by unprecedented natural disasters caused by intense solar activity. As you navigate a city in chaos, you'll act as the head of a team of rescuers tasked with helping people in need.
https://www.youtube.com/watch?v=U7KxN8poHvE&ab_channel=AlawarGames


https://steamcommunity.com/groups/indieg...0320004448

Print this item

  PC - OTXO
Posted by: xSicKxBot - 05-01-2023, 07:07 PM - Forum: New Game Releases - No Replies

OTXO



OTXO (pronounced oh-cho) is a violent top-down shooter with roguelite elements. Play as the protagonist entering an inexplicable mansion in search of his lost love. As you venture deeper into the Mansion, more of its secrets will be unveiled to you.

Featureless, unnamed, and without memories of how you came here but you remember why. She's waiting for you somewhere in this Mansion and you cannot leave until you find her. Cut your way through various unique areas and meet new allies as you delve deeper into the mystery, face your inner demons, and annihilate them.

With a massive variety of guns, over 100 abilities, and Focus to dodge bullets at your disposal, kick down doors and eviscerate the variety of enemies standing in between you and your mission.

Publisher: Lateralis

Release Date: Apr 20, 2023




https://www.metacritic.com/game/pc/otxo

Print this item

  [Tut] Pandas Series Object – A Helpful Guide with Examples
Posted by: xSicKxBot - 05-01-2023, 01:30 AM - Forum: Python - No Replies

Pandas Series Object – A Helpful Guide with Examples

5/5 – (1 vote)

If you’re working with data in Python, you might have come across the pandas library. ?

One of the key components of pandas is the Series object, which is a one-dimensional, labeled array capable of holding data of any type, such as integers, strings, floats, and even Python objects ?.

The Series object serves as a foundation for organizing and manipulating data within the pandas library.

This article will teach you more about this crucial data structure and how it can benefit your data analysis workflows. Let’s get started! ?

Creating a Pandas Series



In this section, you’ll learn how to create a Pandas Series, a powerful one-dimensional labeled array capable of holding any data type.

To create a Series, you can use the Series() constructor from the Pandas library.

Make sure you have Pandas installed and imported:

import pandas as pd

Now, you can create a Series using the pd.Series() function, and pass in various data structures like lists, dictionaries, or even scalar values. For example:

my_list = [1, 2, 3, 4]
my_series = pd.Series(my_list)

The Series() constructor accepts various parameters that help you customize the resulting series, including:

  • data: This is the input data—arrays, dicts, or scalars.
  • index: You can provide a custom index for your series to label the values. If you don’t supply one, Pandas will automatically create an integer index (0, 1, 2…).

Here’s an example of creating a Series with a custom index:

custom_index = ['a', 'b', 'c', 'd']
my_series = pd.Series(my_list, index=custom_index)

When you create a Series object with a dictionary, Pandas automatically takes the keys as the index and the values as the series data:

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
my_series = pd.Series(my_dict)

? Remember: Your Series can hold various data types, including strings, numbers, and even objects.

Pandas Series Indexing



Next, you’ll learn the best ways to index and select data from a Pandas Series, making your data analysis tasks more manageable and enjoyable.

Again, a Pandas Series is a one-dimensional labeled array, and it can hold various data types like integers, floats, and strings. The series object contains an index, which serves multiple purposes, such as metadata identification, automatic and explicit data alignment, and intuitive data retrieval and modification ?.

There are two types of indexing available in a Pandas Series:

  1. Position-based indexing – this uses integer positions to access data. The pandas function iloc[] comes in handy for this purpose.
  2. Label-based indexing – this uses index labels for data access. The pandas function loc[] works great for this type of indexing.
YouTube Video

? Recommended: Pandas loc() and iloc() – A Simple Guide with Video

Let’s examine some examples of indexing and selection in a Pandas Series:

import pandas as pd # Sample Pandas Series
data = pd.Series([10, 20, 30, 40, 50], index=['a', 'b', 'c', 'd', 'e']) # Position-based indexing (using iloc)
position_index = data.iloc[2] # Retrieves the value at position 2 (output: 30) # Label-based indexing (using loc)
label_index = data.loc['b'] # Retrieves the value with the label 'b' (output: 20)

Keep in mind that while working with Pandas Series, the index labels do not have to be unique but must be hashable types. This means they should be of immutable data types like strings, numbers, or tuples ?.

? Recommended: Mutable vs. Immutable Objects in Python

Accessing Values in a Pandas Series



So you’re working with Pandas Series and want to access their values. I already showed you this in the previous section but let’s repeat this once again. Repetition. Repetition. Repetition!

First of all, create your Pandas Series:

import pandas as pd data = ['A', 'B', 'C', 'D', 'E']
my_series = pd.Series(data)

Now that you have your Series, let’s talk about accessing its values ?:

  1. Using index: You can access an element in a Series using its index, just like you do with lists:
third_value = my_series[2]
print(third_value) # Output: C
  1. Using .loc[]: Access an element using its index label with the .loc[] accessor, which is useful when you have custom index names?:
data = ['A', 'B', 'C', 'D', 'E']
index_labels = ['one', 'two', 'three', 'four', 'five']
my_series = pd.Series(data, index=index_labels) second_value = my_series.loc['two']
print(second_value) # Output: B
  1. Using .iloc[]: Access a value based on its integer position with the .iloc[] accessor. This is particularly helpful when you have non-integer index labels?:
value_at_position_3 = my_series.iloc[2]
print(value_at_position_3) # Output: C

Iterating through a Pandas Series



? Although iterating over a Series is possible, it’s generally discouraged in the Pandas community due to its suboptimal performance. Instead, try using vectorization or other optimized methods, such as apply, transform, or agg.

This section will discuss Series iteration methods, but always remember to consider potential alternatives first!

When you absolutely need to iterate through a Series, you can use the iteritems() function, which returns an iterator of index-value pairs. Here’s an example:

for idx, val in your_series.iteritems(): # Do something with idx and val

Another method to iterate over a Pandas Series is by converting it into a list using the tolist() function, like this:

for val in your_series.tolist(): # Do something with val

? However, keep in mind that these approaches are suboptimal and should be avoided whenever possible. Instead, try one of the following efficient techniques:

  • Vectorized operations: Apply arithmetic or comparison operations directly on the Series.
  • Use apply(): Apply a custom function element-wise.
  • Use agg(): Aggregate multiple operations to be applied.
  • Use transform(): Apply a function and return a similarly-sized Series.

Sorting a Pandas Series ?



Sorting a Pandas Series is pretty straightforward. With the sort_values() function, you can easily reorder your series, either in ascending or descending order.

First, you must import the Pandas library and create a Pandas Series:

import pandas as pd
s = pd.Series([100, 200, 54.67, 300.12, 400])

To sort the values in the series, just use the sort_values() function like this:

sorted_series = s.sort_values()

By default, the values will be sorted in ascending order. If you want to sort them in descending order, just set the ascending parameter to False:

sorted_series = s.sort_values(ascending=False)

You can also control the sorting method using the kind parameter. Supported options are 'quicksort', 'mergesort', and 'heapsort'. For example:

sorted_series = s.sort_values(kind='mergesort')

When dealing with missing values (NaN) in your series, you can use the na_position parameter to specify their position in the sorted series. The default value is 'last', which places missing values at the end.

To put them at the beginning of the sorted series, just set the na_position parameter to 'first':

sorted_series = s.sort_values(na_position='first')

Applying Functions to a Pandas Series


You might come across situations where you want to apply a custom function to your Pandas Series. Let’s dive into how you can do that using the apply() method. ?

YouTube Video

To begin with, the apply() method is quite flexible and allows you to apply a wide range of functions on your Series. These functions could be NumPy’s universal functions (ufuncs), built-in Python functions, or user-defined functions. Regardless of the type, apply() will work like magic.?✨

For instance, let’s say you have a Pandas Series containing square numbers, and you want to find the square root of these numbers:

import pandas as pd square_numbers = pd.Series([4, 9, 16, 25, 36])

Now, you can use the apply() method along with the built-in Python function sqrt() to calculate the square root:

import math square_roots = square_numbers.apply(math.sqrt)
print(square_roots)

You’ll get the following output:

0 2.0
1 3.0
2 4.0
3 5.0
4 6.0
dtype: float64

Great job! ? Now, let’s consider you want to create your own function to check if the numbers in a Series are even. Here’s how you can achieve that:

def is_even(number): return number % 2 == 0 even_numbers = square_numbers.apply(is_even)
print(even_numbers)

And the output would look like this:

0 True
1 False
2 True
3 False
4 True
dtype: bool

Congratulations! ? You’ve successfully used the apply() method with a custom function.

Replacing Values in a Pandas Series



You might want to replace specific values within a Pandas Series to clean up your data or transform it into a more meaningful format. The replace() function is here to help you do that! ?

How to use replace()


To use the replace() function, simply call it on your Series object like this: your_series.replace(to_replace, value). to_replace is the value you want to replace, and value is the new value you want to insert instead. You can also use regex for more advanced replacements.

Let’s see an example:

import pandas as pd data = pd.Series([1, 2, 3, 4])
data = data.replace(2, "Two")
print(data)

This code will replace the value 2 with the string "Two" in your Series. ?

Multiple replacements


You can replace multiple values simultaneously by passing a dictionary or two lists to the function. For example:

data = pd.Series([1, 2, 3, 4])
data = data.replace({1: 'One', 4: 'Four'})
print(data)

In this case, 1 will be replaced with 'One' and 4 with 'Four'. ?

Limiting replacements


You can limit the number of replacements by providing the limit parameter. For example, if you set limit=1, only the first occurrence of the value will be replaced.

data = pd.Series([2, 2, 2, 2])
data = data.replace(2, "Two", limit=1)
print(data)

This code will replace only the first occurrence of 2 with "Two" in the Series. ✨

Appending and Concatenating Pandas Series


You might want to combine your pandas Series while working with your data. Worry not! ? Pandas provides easy and convenient ways to append and concatenate your Series.

Appending Series


Appending Series can be done using the append() method. It allows you to concatenate two or more Series objects. To use it, simply call the method on one series and pass the other series as the argument.

For example:

import pandas as pd series1 = pd.Series([1, 2, 3])
series2 = pd.Series([4, 5, 6]) result = series1.append(series2)
print(result)

Output:

0 1
1 2
2 3
0 4
1 5
2 6
dtype: int64

However, appending Series iteratively may become computationally expensive. In such cases, consider using concat() instead. ?

Concatenating Series


The concat() function is more efficient when you need to combine multiple Series vertically. Simply provide a list of Series you want to concatenate as its argument, like so:

import pandas as pd series_list = [ pd.Series(range(1, 6), index=list('abcde')), pd.Series(range(1, 6), index=list('fghij')), pd.Series(range(1, 6), index=list('klmno'))
] combined_series = pd.concat(series_list)
print(combined_series)

Output:

a 1
b 2
c 3
d 4
e 5
f 1
g 2
h 3
i 4
j 5
k 1
l 2
m 3
n 4
o 5
dtype: int64

? There you have it! You’ve combined your Pandas Series using append() and concat().

Renaming a Pandas Series



Renaming a Pandas Series is a simple yet useful operation you may need in your data analysis process.

To start, the rename() method in Pandas can be used to alter the index labels or name of a given Series object. But, if you just want to change the name of the Series, you can set the name attribute directly. For instance, if you have a Series object called my_series, you can rename it to "New_Name" like this:

my_series.name = "New_Name"

Now, let’s say you want to rename the index labels of your Series. You can do this using the rename() method. Here’s an example:

renamed_series = my_series.rename(index={"old_label1": "new_label1", "old_label2": "new_label2"})

The rename() method also accepts functions for more complex transformations. For example, if you want to capitalize all index labels, you can do it like this:

capitalized_series = my_series.rename(index=lambda x: x.capitalize())

Keep in mind that the rename() method creates a new Series by default and doesn’t modify the original one. If you want to change the original Series in-place, just set the inplace argument to True:

my_series.rename(index={"old_label1": "new_label1", "old_label2": "new_label2"}, inplace=True)

Unique Values in a Pandas Series



To find unique values in a Pandas Series, you can use the unique() method?. This method returns the unique values in the series without sorting them, maintaining the order of appearance.

Here’s a quick example:

import pandas as pd data = {'A': [1, 2, 1, 4, 5, 4]}
series = pd.Series(data['A']) unique_values = series.unique()
print(unique_values)

The output will be: [1, 2, 4, 5]

When working with missing values, keep in mind that the unique() method includes NaN values if they exist in the series. This behavior ensures you are aware of missing data in your dataset ?.

If you need to find unique values in multiple columns, the unique() method might not be the best choice, as it only works with Series objects, not DataFrames. Instead, use the .drop_duplicates() method to get unique combinations of multiple columns.

? Recommended: The Ultimate Guide to Data Cleaning in Python and Pandas

To summarize, when finding unique values in a Pandas Series:

  • Use the unique() method for a single column ?
  • Remember that NaN values will be included as unique values when present ?
  • Use the .drop_duplicates() method for multiple columns when needed ?

With these tips, you’re ready to efficiently handle unique values in your Pandas data analysis! ??

Converting Pandas Series to Different Data Types



You can convert a Pandas Series to different data types to modify your data and simplify your work. In this section, you’ll learn how to transform a Series into a DataFrame, List, Dictionary, Array, String, and Numpy Array. Let’s dive in! ?

Series to DataFrame


To convert a Series to a DataFrame, use the to_frame() method. Here’s how:

import pandas as pd data = pd.Series([1, 2, 3, 4])
df = data.to_frame()
print(df)

This code will output:

 0
0 1
1 2
2 3
3 4

Series to List


For transforming a Series to a List, simply call the tolist() method, like this:

data_list = data.tolist()
print(data_list)

Output:

[1, 2, 3, 4]

Series to Dictionary


To convert your Series into a Dictionary, use the to_dict() method:

data_dict = data.to_dict()
print(data_dict)

This results in:

{0: 1, 1: 2, 2: 3, 3: 4}

The keys are now indexes, and the values are the original Series data.

Series to Array


Convert your Series to an Array by accessing its .array attribute:

data_array = data.array
print(data_array)

Output:

<PandasArray>
[1, 2, 3, 4]

Series to String


To join all elements of a Series into a single String, use the join() function from the str library:

data_str = ''.join(map(str, data))
print(data_str)

This will result in:

1234

Series to Numpy Array


For converting a Series into a Numpy Array, call the to_numpy() method:

import numpy as np data_numpy = data.to_numpy()
print(data_numpy)

Output:

array([1, 2, 3, 4], dtype=int64)

Now you’re all set to manipulate your Pandas Series objects and adapt them to different data types! ?

Python Pandas Series in Practice ??



A Pandas Series is a one-dimensional array-like object that’s capable of holding any data type. It’s one of the essential data structures in the Pandas library, along with the DataFrame. Series is an easy way to organize and manipulate your data, especially when dealing with labeled data, such as SQL databases or dictionary keys. ?⚡

To begin, import the Pandas library, which is usually done with the alias ‘pd‘:

import pandas as pd

Creating a Pandas Series ??


To create a Series, simply pass a list, ndarray, or dictionary to the pd.Series() function. For example, you can create a Series with integers:

integer_series = pd.Series([1, 2, 3, 4, 5])

Or with strings:

string_series = pd.Series(['apple', 'banana', 'cherry'])

In case you want your Series to have an explicit index, you can specify the index parameter:

indexed_series = pd.Series(['apple', 'banana', 'cherry'], index=['a', 'b', 'c'])

Accessing and Manipulating Series Data ??


Now that you have your Series, here’s how you can access and manipulate the data:

  • Accessing data by index (using both implicit and explicit index):
    • First item: integer_series[0] or indexed_series['a']
    • Slicing: integer_series[1:3]
  • Adding new data:
    • Append: string_series.append(pd.Series(['date']))
    • Add with a label: indexed_series['d'] = 'date'
  • Common Series methods:
    • all() – Check if all elements are true
    • any() – Check if any elements are true
    • unique() – Get unique values
    • ge(another_series) – Compare elements element-wise with another Series

These are just a few examples of interacting with a Pandas Series. There are many other functionalities you can explore!

Practice makes perfect, so feel free to join our free email academy where I’ll show you practical coding projects, data science, exponential technologies in AI and blockchain engineering, Python, and much more. How can you join? Simply download your free cheat sheets by entering your name here:

Let your creativity run wild and happy coding! ??



https://www.sickgaming.net/blog/2023/04/...-examples/

Print this item

  (Indie Deal) Giveaways, Wall World, Sales
Posted by: xSicKxBot - 05-01-2023, 01:30 AM - Forum: Deals or Specials - No Replies

Giveaways, Wall World, Sales

[www.indiegala.com]
Explore the mysterious Wall World on your giant robospider: mine for valuable resources, upgrade your equipment to fight off hordes of monsters, and discover exotic biomes in-between attacks. Will you be able to survive and learn the secrets of the Wall World?
https://www.youtube.com/watch?v=DYHQezOlvh8&ab_channel=AlawarPremium
Sales:
[www.indiegala.com]
#16 Dev Update



https://steamcommunity.com/groups/indieg...0023358173

Print this item

 
Latest Threads
News - GameStop Is Not Hu...
Last Post: xSicKxBot
6 hours ago
Lemfi Rebrand + World Cup...
Last Post: Sazzy01
9 hours ago
World Cup 2026 Lemfi Foun...
Last Post: Sazzy01
9 hours ago
World Cup 2026 Nigeria Le...
Last Post: Sazzy01
9 hours ago
World Cup 2026 Canada Off...
Last Post: Sazzy01
9 hours ago
World Cup 2026 Lemfi UK C...
Last Post: Sazzy01
9 hours ago
Lemfi Wiki + World Cup 20...
Last Post: Sazzy01
9 hours ago
Lemfi Transfer Time + Wor...
Last Post: Sazzy01
9 hours ago
Lemfi USA World Cup 2026 ...
Last Post: Sazzy01
9 hours ago
Apollo Neuro Discount Cod...
Last Post: lex9090bb
9 hours ago

Forum software by © MyBB Theme © iAndrew 2016