'convert whole List from Float to integer in Pandas
Im new to Pandas. I have fetched some values from the database, created a dataframe and used this dataframe to create a pivot table. The problem i am facing is, that if i loop through the list, the integer values are per default floats. I want them to be integers.
so here is my code:
resTable = cur.fetchall()
colNames = cur.column_names
df = pd.DataFrame(resTable, columns = colNames)
result = dfTable.to_json(orient='split')
jsonResult = json.loads(result)
dataTable = jsonResult['data']
for dt in dataTable:
print(dt)
the results i got from this loop are the following:
[1.0, 1.0, 1.0]
[1.0, 1.0, 1.0]
[1.0, 1.0, 1.0]
[None, 1.0, None]
is there a way to parse each value to integer in pandas? or to set the default to integer? Thank you for help
Solution 1:[1]
use apply and pandas.to_numeric to convert your values and replace NaN values using astype(int), for example:
import pandas as pd
df=pd.DataFrame([[1.0, 1.0, 1.0],[1.0, 1.0, 1.0],[1.0, 1.0, 1.0],[None, 1.0, None]], columns=['a','b','c'])
df=df.apply(pd.to_numeric, errors="ignore")
df.fillna(0).astype(int)
Output
a b c
0 1.0 1.0 1.0
1 1.0 1.0 1.0
2 1.0 1.0 1.0
3 NaN 1.0 NaN
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ellhe-blaster |
