Categories
Python Answers

How to add Python Pandas data to an existing CSV file?

Sometimes, we want to add Python Pandas data to an existing CSV file.

In this article, we’ll look at how to add Python Pandas data to an existing CSV file.

How to add Python Pandas data to an existing CSV file?

To add Python Pandas data to an existing CSV file, we can use the df.to_csv method.

For instance, we write:

import pandas as pd

df = pd.read_csv('foo.csv', index_col=0)
with open('foo.csv', 'a') as f:
    (df + 5).to_csv(f, header=False)

to read the content of foo.csv with read_csv.

Then we call open with 'foo.csv' to open the file with 'a' permission, which is append.

And we call to_csv on df + 5 with file f to append the new values to foo.csv.

We set header to False to skip adding headers.

Therefore, if foo.txt originally has:

,A,B,C
0,1,2,3
1,4,5,6

Then we get:

,A,B,C
0,1,2,3
1,4,5,6
0,6,7,8
1,9,10,11

after calling to_csv on df + 5.

Conclusion

To add Python Pandas data to an existing CSV file, we can use the df.to_csv method.

Categories
Python Answers

How to get list of values from a Python dict?

Sometimes, we want to get list of values from a Python dict.

In this article, we’ll look at how to get list of values from a Python dict.

How to get list of values from a Python dict?

To get list of values from a Python dict, we can use the dict’s values method and the list function.

For instance, we write:

d = {'a': 1, 'b': 2}
v = list(d.values())
print(v)

We call d.values to return a view of the values.

Then we use the list function to convert the values view into a list.

Therefore, v is [1, 2].

Conclusion

To get list of values from a Python dict, we can use the dict’s values method and the list function.

Categories
Python Answers

How to convert an XML file to a Pandas DataFrame?

Sometimes, we want to convert an XML file to a Pandas DataFrame.

In this article, we’ll look at how to convert an XML file to a Pandas DataFrame.

How to convert an XML file to a Pandas DataFrame?

To convert an XML file to a Pandas DataFrame, we can use the xml.etree.ElementTree module.

For instance, we write:

import pandas as pd
import xml.etree.ElementTree as ET

xml_str = '''<?xml version="1.0" encoding="utf-8"?>
<response>
  <head>
    <code>   200  </code>
  </head>
  <body>
    <data id="0" name="All Categories" t="2018052600" tg="1" type="category"/>
    <data id="13" name="RealEstate.com.au [H]" t="2018052600" tg="1" type="publication"/>
  </body>
</response>
'''

etree = ET.fromstring(xml_str)
dfcols = ['id', 'name']
df = pd.DataFrame(columns=dfcols)

for i in etree.iter(tag='data'):
    df = df.append(pd.Series([i.get('id'), i.get('name')], index=dfcols),
                   ignore_index=True)

h = df.head()
print(h)

We have an XML string assigned to xml_str.

And we parse it by passing that as the argument of ET.fromstring.

Next, we define the columns of the DataFrame.

And we create the DataFrame with the DataFrame constructor.

Next, we loop through the parsed XML data elements we got with etree.iter(tag='data') with the for loop.

And we call df.append to append to id and name attribute values by putting them into a series.

Then we get the first 5 rows with df.head.

Therefore, print should print:

   id                   name
0   0         All Categories
1  13  RealEstate.com.au [H]

Conclusion

To convert an XML file to a Pandas DataFrame, we can use the xml.etree.ElementTree module.

Categories
Python Answers

How to calculate time difference between two Python Pandas columns in hours and minutes?

Sometimes, we want to calculate time difference between two Python Pandas columns in hours and minutes.

In this article, we’ll look at how to calculate time difference between two Python Pandas columns in hours and minutes.

How to calculate time difference between two Python Pandas columns in hours and minutes?

To calculate time difference between two Python Pandas columns in hours and minutes, we can subtract the datetime objects directly.

For instance, we write:

import pandas

df = pandas.DataFrame(columns=['to', 'fr', 'ans'])
df.to = [
    pandas.Timestamp('2020-01-24 13:03:12.050000'),
    pandas.Timestamp('2020-01-27 11:57:18.240000'),
    pandas.Timestamp('2020-01-23 10:07:47.660000')
]
df.fr = [
    pandas.Timestamp('2020-01-26 23:41:21.870000'),
    pandas.Timestamp('2020-01-27 15:38:22.540000'),
    pandas.Timestamp('2020-01-23 18:50:41.420000')
]
df.ans = (df.fr - df.to).astype('timedelta64[h]')
print(df)

We create a Panda DataFrame with 3 columns.

Then we set the values of the to and fr columns to Pandas timestamps.

Next, we subtract the values from df.fr by df.toand convert the type totimedelta64withastypeand assign that todf.ans`.

Therefore, df is:

                       to                      fr   ans
0 2020-01-24 13:03:12.050 2020-01-26 23:41:21.870  58.0
1 2020-01-27 11:57:18.240 2020-01-27 15:38:22.540   3.0
2 2020-01-23 10:07:47.660 2020-01-23 18:50:41.420   8.0

according to what’s printed.

Conclusion

To calculate time difference between two Python Pandas columns in hours and minutes, we can subtract the datetime objects directly.

Categories
Python Answers

How to get the ASCII value of a character with Python?

Sometimes, we want to get the ASCII value of a character with Python.

In this article, we’ll look at how to get the ASCII value of a character with Python.

How to get the ASCII value of a character with Python?

To get the ASCII value of a character with Python, we can use the chr function.

For instance, we write:

c = chr(97)
print(c)

We call chr with the ASCII character code for ‘a’.

And then we assign the return character string to c.

Therefore, c is 'a'.

Conclusion

To get the ASCII value of a character with Python, we can use the chr function.