【问题标题】:How to split strings inside a numpy array?如何在numpy数组中拆分字符串?
【发布时间】:2018-01-20 16:18:43
【问题描述】:

我有下表:

由于“位置”列中的状态重复,我试图从位置中删除状态,以便它只有城市名称。

year    location    state   success
2009    New York, NY    NY  1
2009    New York, NY    NY  1
2009    Chicago, IL IL  1
2009    New York, NY    NY  1
2009    Boston, MA  MA  1
2009    Long Beach, CA  CA  1
2009    Atlanta, GA GA  1

我已经尝试了以下代码:

x = KS_clean.column(1)
np.chararray.split(x, ',')

如何拆分字符串,使结果只包含城市名称,如下所示:

array('New York', 'New York', 'Chicago', ...,) 

这样我可以把它放回桌子里吗?

对不起,这是一个基本问题,但我是 python 新手,还在学习。谢谢

【问题讨论】:

  • 你的数据看起来像一个 pandas DataFrame,而不是一个 numpy 数组。请检查。
  • 这是一个熊猫数据框,但是当我提取列 (var x) 并检查其类型时,它显示为 numpy.ndarray
  • 您最初是如何获得数据框的?看起来很奇怪。当你选择一列时,你必须得到一个Series,而不是任何numpy。

标签: python string numpy


【解决方案1】:

我认为您需要先与DataFrame 合作(例如read_csv):

import numpy as np
from pandas.compat import StringIO

temp=u"""year;location;state;success
2009;New York, NY;NY;1
2009;New York, NY;NY;1
2009;Chicago, IL;IL;1
2009;New York, NY;NY;1
2009;Boston, MA;MA;1
2009;Long Beach, CA;CA;1
2009;Atlanta, GA;GA;1"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp), sep=";")

print (type(df))
<class 'pandas.core.frame.DataFrame'>

print (df)
   year        location state  success
0  2009    New York, NY    NY        1
1  2009    New York, NY    NY        1
2  2009     Chicago, IL    IL        1
3  2009    New York, NY    NY        1
4  2009      Boston, MA    MA        1
5  2009  Long Beach, CA    CA        1
6  2009     Atlanta, GA    GA        1

然后按str.split 拆分并按str[0] 选择第一个列表:

df['location'] = df['location'].str.split(', ').str[0]
print (df)
   year    location state  success
0  2009    New York    NY        1
1  2009    New York    NY        1
2  2009     Chicago    IL        1
3  2009    New York    NY        1
4  2009      Boston    MA        1
5  2009  Long Beach    CA        1
6  2009     Atlanta    GA        1

如有必要,最后通过values 转换为 numpy 数组:

arr = df.values
print (arr)
[[2009 'New York' 'NY' 1]
 [2009 'New York' 'NY' 1]
 [2009 'Chicago' 'IL' 1]
 [2009 'New York' 'NY' 1]
 [2009 'Boston' 'MA' 1]
 [2009 'Long Beach' 'CA' 1]
 [2009 'Atlanta' 'GA' 1]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多