繁体   English   中英

使用 python pandas 将一列拆分为两列

[英]Split one column into two columns with python pandas

我有一个城市的df,显示为:

| id | location         |
|----|------------------|
| 1  | New York (NY)    |
| 2  | Los Angeles (CA) |
| 3  | Houston (TX)     |

我希望使用某种拆分/条带,给我类似的东西

| id | city             | state |
|----|------------------|-------|
| 1  | New York         |   NY  |
| 2  | Los Angeles      |   CA  |
| 3  | Houston          |   TX  |

或者即使是三列,一是原始的,二是由代码制成的。 我已经尝试过类似的东西:

df[['city', 'state']] = df['location'].str.split("(", expand=True)
df['state'] = df['state'].str.strip(")")

哪个有效,但不是那么多,因为每个城市名称后面都有一个空格,不应该。 如果我搜索一个城市,例如:

df[df['city'] == 'Houston'] 

它不会返回任何内容,但我必须编写如下代码:

df[df['city'] == 'Houston '] # note the empty space after code

给我一些有用的东西,但是当我进行合并或类似的事情时,那样会让我头疼。

那么,有人对这段代码有一些技巧吗? 我在互联网上找不到任何有用的东西。 它总是一个简单的分割,或者一个简单的条带。 但我相信有一种更智能的模式可以做到这一点。

好吧,为什么不df['city'] = df['city'].strip()

使用str.extract

df = df.join(df.pop('location').str.extract(r'(.*)\s*\((.*)\)')
               .rename(columns={0: 'location', 1: 'state'}))
print(df)

# Output
   id      location state
0   1     New York     NY
1   2  Los Angeles     CA
2   3      Houston     TX

暂无
暂无

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

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