Skip to content

Instantly share code, notes, and snippets.

@Keiku
Created January 19, 2018 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Keiku/9eca1e217abf00713f88c667751794db to your computer and use it in GitHub Desktop.
Save Keiku/9eca1e217abf00713f88c667751794db to your computer and use it in GitHub Desktop.
Read copy text to pandas DataFrame.
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