Created
January 19, 2018 10:25
-
-
Save Keiku/9eca1e217abf00713f88c667751794db to your computer and use it in GitHub Desktop.
Read copy text to pandas DataFrame.
This file contains hidden or 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 io import StringIO | |
def read_copytext(text): | |
text1 = StringIO(text) | |
df = pd.read_table(text1) | |
df.columns = ["col1"] | |
df["col1"] = df["col1"].str.replace("\s+", ",") | |
df = df["col1"].str.split(',', expand=True) | |
text2 = StringIO(text) | |
df_columns = pd.read_table(text2, usecols=[0], header=None) | |
columns = pd.Series(df_columns.iloc[0, :].squeeze()) | |
columns = columns.str.replace("\s+", ",") | |
columns = columns.str.split(',').tolist() | |
columns = columns[0] | |
df.columns = columns | |
df = df.drop([""], axis=1) | |
return df | |
copy_text = """ AAPL GOOG MSFT AMZN FB | |
1 NaN NaN 9.731 NaN NaN | |
2 NaN 4.5 NaN 3.486 NaN | |
3 4.331 NaN NaN 3.26 5.967 | |
4 NaN NaN NaN NaN 3.61""" | |
df = read_copytext(copy_text) | |
AAPL GOOG MSFT AMZN FB | |
0 NaN NaN 9.731 NaN NaN | |
1 NaN 4.5 NaN 3.486 NaN | |
2 4.331 NaN NaN 3.26 5.967 | |
3 NaN NaN NaN NaN 3.61 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment