我正在尝试将文本文件解析为两列。该文件遵循两个地址的结构,一次是第一个地址需要进入第一列,第二个地址需要进入第二列。然后需要在注释行(########################
)之后每两个地址重复一次
结构如下:
import pandas as pd
pd.read_clipboard('''
Arnie Morton's of Chicago 435 S. La Cienega Blvd. Los Angeles 310-246-1501 Steakhouses
Arnie Morton's of Chicago 435 S. La Cienega Blvd. Los Angeles 310/246-1501 American
########################
Art's Deli 12224 Ventura Blvd. Studio City 818-762-1221 Delis
Art's Delicatessen 12224 Ventura Blvd. Studio City 818/762-1221 American
########################
Bel-Air Hotel 701 Stone Canyon Rd. Bel Air 310-472-1211 Californian
Hotel Bel-Air 701 Stone Canyon Rd. Bel Air 310/472-1211 Californian
########################
Cafe Bizou 14016 Ventura Blvd. Sherman Oaks 818-788-3536 French Bistro
Cafe Bizou 14016 Ventura Blvd. Sherman Oaks 818/788-3536 French
########################
Campanile 624 S. La Brea Ave. Los Angeles 213-938-1447 Californian
Campanile 624 S. La Brea Ave. Los Angeles 213/938-1447 American
''', comment='#')
我需要将文件解析为如下所示的pandas数据框(前两个地址的示例):
'<table border="1" class="dataframe">\n <thead>\n <tr style="text-align: right;">\n <th></th>\n <th>address1</th>\n <th>address2</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>Arnie Morton\'s of Chicago 435 S. La Cienega Blvd. Los Angeles 310-246-1501 Steakhouses</td>\n <td>Arnie Morton\'s of Chicago 435 S. La Cienega Blvd. Los Angeles 310/246-1501 American</td>\n </tr>\n </tbody>\n</table>'
有人有什么建议吗?
答案 0 :(得分:2)
不确定我是否遵循剪贴板部分,但是从您的字符串示例中,这是一个解决方案:
import pandas as pd
import numpy as np
lines = """...your lines..."""
# strip empty lines and comments
data = np.array([s for s in
(l for l in s.split('\n') if len(l) and not l.startswith('#'))
])
# create the dataframe, using np.reshape to create 2 columns
df = pd.DataFrame(data.reshape((-1,2)), columns=['addr_1', 'addr_2'])
这将在结构一致的情况下起作用:地址始终为2比2,所有注释均以“#”开头,空行实际上为空(没有空格)。