Last active
October 5, 2015 08:32
-
-
Save YS-L/5ad130a2a61a93e223c8 to your computer and use it in GitHub Desktop.
Convert a human readable DataFrame representation to an actual DataFrame
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
from functools import wraps | |
@wraps(pd.read_csv) | |
def to_dataframe(s, sep='[\s]+', **kwargs): | |
""" | |
Convert a human readable DataFrame representation to an actual DataFrame | |
s : string | |
Returns | |
------- | |
df : DataFrame | |
""" | |
df = pd.read_csv(pd.core.common.StringIO(s), sep=sep, **kwargs) | |
return df | |
def test1(): | |
s = """ | |
date hour1 hour2 hour3 hour4 | |
2012-12-31 9.18 -0.10 -7.00 -64.92 | |
2012-12-30 13.91 0.09 -0.96 0.08 | |
2012-12-29 12.97 11.82 11.65 10.20 | |
2012-12-28 22.01 16.04 15.68 11.67 | |
2012-12-27 11.44 0.07 -19.97 -67.98 | |
""" | |
df = to_dataframe(s) | |
print df | |
print df.dtypes | |
def test2(): | |
input_with_unnamed_index = """ | |
date hour1 hour2 hour3 hour4 | |
0 2012-12-31 9.18 -0.10 -7.00 -64.92 | |
1 2012-12-30 13.91 0.09 -0.96 0.08 | |
2 2012-12-29 12.97 11.82 11.65 10.20 | |
3 2012-12-28 22.01 16.04 15.68 11.67 | |
4 2012-12-27 11.44 0.07 -19.97 -67.98 | |
""" | |
df = to_dataframe(input_with_unnamed_index) | |
print df | |
print df.dtypes | |
if __name__ == '__main__': | |
test1() | |
test2() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment