如何将第二行解析为第二列

2024-04-29 06:30:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图把一个文本文件分为两列。文件遵循两个地址的结构,第一个地址需要进入第一列,第二个地址需要进入第二列。然后需要在注释行(########################)之后的每两个地址重复一次

结构如下所示:

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='#')

我需要将文件解析为如下所示的数据帧(前两个地址的示例):

'<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>'

有人有什么建议吗


Tags: of地址airlamortonamericanbelth
1条回答
网友
1楼 · 发布于 2024-04-29 06:30:47

我不确定是否遵循剪贴板部分,但根据您的字符串示例,这里有一个解决方案:

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'])

只要结构是一致的,这就可以工作:地址总是两乘二,所有注释都以“#”开头,空行实际上是空的(没有空格)

相关问题 更多 >