将标准输入转换为数据帧
Converting standard input to dataframe
我有标准输入:
'Town3, NYC, Town1, Town4, Town5, Town6, Town2
67, 69, 60, 63, 65, 69, 95'
我想知道如何将其转换为 pandas 数据框,以便我得到:
Town3 NYC Town1 Town4 Town5 Town6 Town2
0 67 69 60 63 65 69 95
您可以使用 io.StringIO
+ pd.read_csv
:
import pandas as pd
from io import StringIO
s = """Town3, NYC, Town1, Town4, Town5, Town6, Town2
67, 69, 60, 63, 65, 69, 95"""
df = pd.read_csv(
StringIO(s),
sep=r",\s*",
engine="python",
)
print(df)
打印:
Town3 NYC Town1 Town4 Town5 Town6 Town2
0 67 69 60 63 65 69 95
将您的字符串拆分到列表中。把它切成两等份。第一部分是列,第二部分是值:
s = 'Town3, NYC, Town1, Town4, Town5, Town6, Town2, 67, 69, 60, 63, 65, 69, 95'
l = s.split(', ')
df = pd.DataFrame([l[len(l)//2:]], columns=l[:len(l)//2])
>>> df
Town3 NYC Town1 Town4 Town5 Town6 Town2
0 67 69 60 63 65 69 95
我有标准输入:
'Town3, NYC, Town1, Town4, Town5, Town6, Town2
67, 69, 60, 63, 65, 69, 95'
我想知道如何将其转换为 pandas 数据框,以便我得到:
Town3 NYC Town1 Town4 Town5 Town6 Town2
0 67 69 60 63 65 69 95
您可以使用 io.StringIO
+ pd.read_csv
:
import pandas as pd
from io import StringIO
s = """Town3, NYC, Town1, Town4, Town5, Town6, Town2
67, 69, 60, 63, 65, 69, 95"""
df = pd.read_csv(
StringIO(s),
sep=r",\s*",
engine="python",
)
print(df)
打印:
Town3 NYC Town1 Town4 Town5 Town6 Town2
0 67 69 60 63 65 69 95
将您的字符串拆分到列表中。把它切成两等份。第一部分是列,第二部分是值:
s = 'Town3, NYC, Town1, Town4, Town5, Town6, Town2, 67, 69, 60, 63, 65, 69, 95'
l = s.split(', ')
df = pd.DataFrame([l[len(l)//2:]], columns=l[:len(l)//2])
>>> df
Town3 NYC Town1 Town4 Town5 Town6 Town2
0 67 69 60 63 65 69 95