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.

Categories
Python Answers

How to find overlapping matches with a regex with Python?

Sometimes, we want to find overlapping matches with a regex with Python.

In this article, we’ll look at how to find overlapping matches with a regex with Python.

How to find overlapping matches with a regex with Python?

To find overlapping matches with a regex with Python, we can use the re.finall method with the r'(?=(\w\w))' regex string.

We have (?=...) to add a lookahead assertion to let us find overlapping matches.

For instance, we write:

import re

matches = re.findall(r'(?=(\w\w))', 'hello')
print(matches)

We call re.findall with the regex string and the string we want to find the matches for.

Therefore, matches is:

['he', 'el', 'll', 'lo']

Conclusion

To find overlapping matches with a regex with Python, we can use the re.finall method with the r'(?=(\w\w))' regex string.

We have (?=...) to add a lookahead assertion to let us find overlapping matches.

Categories
Python Answers

How to convert between datetime, timestamp and datetime64 with Python?

Sometimes, we want to convert between datetime, timestamp and datetime64 with Python.

In this article, we’ll look at how to convert between datetime, timestamp and datetime64 with Python.

How to convert between datetime, timestamp and datetime64 with Python?

To convert between datetime, timestamp and datetime64 with Python, we can use the Pandas’ Timestamp class to create a Pandas timestamp.

And we can use the numpy’s datetime64 method to create a numpy date time object.

For instance, we write:

import numpy as np
import pandas as pd

ts = pd.Timestamp(np.datetime64('2020-05-01T01:00:00.000000'))
print(ts)

dt = np.datetime64('2012-05-01T01:00:00.000000+0100')
print(dt)

We call pd.Timestamp with a nummpy datetime64 object to convert it to a Pandas timestamp.

Then we call the np.datetime64 method with a date time string to convert it to a numpy’s date time 64 object.

Therefore, ts is 2020-05-01 01:00:00.

And dt is 2012-05-01T00:00:00.000000.

Conclusion

To convert between datetime, timestamp and datetime64 with Python, we can use the Pandas’ Timestamp class to create a Pandas timestamp.

And we can use the numpy’s datetime64 method to create a numpy date time object.

Categories
Python Answers

How to split a string and keep the separators with Python?

Sometimes, we want to split a string and keep the separators with Python.

In this article, we’ll look at how to split a string and keep the separators with Python.

How to split a string and keep the separators with Python?

To split a string and keep the separators with Python, we can use the re.split method with the '(\W)' pattern.

For instance, we write:

import re

a = re.split('(\W)', 'foo/bar spam\neggs')
print(a)

We call re.split with '(\W)' and the string we want to split into an array of substrings and assign the array to a.

Therefore, a is ['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs'].

Conclusion

To split a string and keep the separators with Python, we can use the re.split method with the '(\W)' pattern.