繁体   English   中英

如何将第二行解析为熊猫的第二列

[英]How to parse every second row into the second column in pandas

我正在尝试将文本文件解析为两列。 该文件遵循两个地址的结构,一次是第一个地址需要进入第一列,第二个地址需要进入第二列。 然后需要在注释行之后为每两个地址重复一次( ########################

结构如下:

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

有人有什么建议吗?

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

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,所有注释均以“#”开头,​​空行实际上是空的(没有空格)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM