Categories
Python Answers

How to fix the “datetime.datetime not JSON serializable” error in Python?

Sometimes, we’ve to fix the "datetime.datetime not JSON serializable" error in Python.

In this article, we’ll look at how to fix the "datetime.datetime not JSON serializable" error in Python.

How to fix the "datetime.datetime not JSON serializable" error in Python?

To fix the "datetime.datetime not JSON serializable" error in Python, we can use the json.dumps method.

For instance, we write:

from datetime import date, datetime
from json import dumps


def json_serial(obj):
    if isinstance(obj, (datetime, date)):
        return obj.isoformat()
    raise TypeError("Type %s not serializable" % type(obj))


s = dumps(datetime.now(), default=json_serial)
print(s)

We create the json_serial function to serialize the datetime object into a string.

In the function,. we call isinstance with obj and (datetime, date) to check if obj that we’re trying to serialize is a date or datetime object.

If it is, then we return obj.isoformat to return a date string.

Otherwise, we raise a TypeError.

Next, we call dumps with a datetime object and set default to json_serial to use json_serial to do the serialization.

Therefore s is "2021-10-20T00:13:35.533502".

Conclusion

To fix the "datetime.datetime not JSON serializable" error in Python, we can use the json.dumps method.

Categories
Python Answers

How to replace NaN values by zeroes in a column of a Python Pandas Dataframe?

Sometimes, we want to replace NaN values by zeroes in a column of a Python Pandas Dataframe.

In this article, we’ll look at how to replace NaN values by zeroes in a column of a Python Pandas Dataframe.

How to replace NaN values by zeroes in a column of a Python Pandas Dataframe?

To replace NaN values by zeroes in a column of a Python Pandas Dataframe, we can use the DataFrame’s fillna method.

For instance, we write:

import pandas as pd

df = pd.DataFrame({'col': [1, 2, 3, None, None]}).fillna(0)
print(df)

We create a DataFrame with pd.DataFrame({'col': [1, 2, 3, None, None]}).

None are the NaN values in the DataFrame.

Then we call fillna to replace None with 0 and assign the DataFrame to df.

Therefore, df is:

   col
0  1.0
1  2.0
2  3.0
3  0.0
4  0.0

Conclusion

To replace NaN values by zeroes in a column of a Python Pandas Dataframe, we can use the DataFrame’s fillna method.

Categories
Python Answers

How to create a list with a single item repeated N times with Python?

Sometimes, we want to create a list with a single item repeated N times with Python.

In this article, we’ll look at how to create a list with a single item repeated N times with Python.

How to create a list with a single item repeated N times with Python?

To create a list with a single item repeated N times with Python, we can use the * operator with a list and the number of items to repeat.

For instance, we write:

my_list = ['foo'] * 10
print(my_list)

We define my_list by using an list and 10 as an operand to return a list with 'foo' repeated 10 times.

Therefore, my_list is ['foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo'].

Conclusion

To create a list with a single item repeated N times with Python, we can use the * operator with a list and the number of items to repeat.

Categories
Python Answers

How to write a list to a file with Python?

Sometimes, we want to write a list to a file with Python.

In this article, we’ll look at how to write a list to a file with Python.

How to write a list to a file with Python?

To write a list to a file with Python, we can open the file with open.

Then we loop through the list items with a for loop and call f.write on each item.

For instance, we write:

my_list = [1, 2, 3]

with open('your_file.txt', 'w') as f:
    for item in my_list:
        f.write("%s\n" % item)

We call open with the path to the text file we want to write to.

'w' lets us write to the file.

Then we loop through my_list and call f.write in the loop body.

Therefore, your_file.txt has:

1
2
3

as its content.

Conclusion

To write a list to a file with Python, we can open the file with open.

Then we loop through the list items with a for loop and call f.write on each item.

Categories
Python Answers

How to convert JSON to Pandas DataFrame with Python?

Sometimes, we want to convert JSON to Pandas DataFrame with Python.

In this article, we’ll look at how to convert JSON to Pandas DataFrame with Python.

How to convert JSON to Pandas DataFrame with Python?

To convert JSON to Pandas DataFrame with Python, we can use the json.loads method to load the JSON string into a dictionary.

Then we call Panda’s json_normalize function to convert the JSON to a data frame.

For instance, we write:

import pandas as pd
import json

j = '''
{
    "results": [{
        "elevation": 243.3462677001953,
        "location": {
            "lat": 42.97404,
            "lng": -81.205203
        },
        "resolution": 19.08790397644043
    }, {
        "elevation": 244.1318664550781,
        "location": {
            "lat": 42.974298,
            "lng": -81.19575500000001
        },
        "resolution": 19.08790397644043
    }],
    "status": "OK"
}
'''

data = json.loads(j)
df = pd.json_normalize(data['results'])
print(df)

We call json.loads with the j JSON string to load the JSON string into a dictionary.

Then we call pd.json_normalize with the values we want to convert into a DataFrame and assign that to df.

Therefore, df is:

    elevation  resolution  location.lat  location.lng
0  243.346268   19.087904     42.974040    -81.205203
1  244.131866   19.087904     42.974298    -81.195755

Conclusion

To convert JSON to Pandas DataFrame with Python, we can use the json.loads method to load the JSON string into a dictionary.

Then we call Panda’s json_normalize function to convert the JSON to a data frame.