如何在numpy数组中拆分字符串?

4
我有以下表格:
由于“位置”列中重复出现了州名,我试图将州名从“位置”中删除,以便仅保留城市名称。
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数组。请检查一下。 - DYZ
这是一个 pandas DataFrame,但当我提取列(变量 x)并检查其类型时,它显示为 numpy.ndarray。 - Hamza Khawar
你最开始是怎么得到这个数据框的?它看起来很奇怪。当你选择一列时,你必须得到一个Series,而不是任何numpy东西。 - DYZ
1个回答

4

我认为您需要先使用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]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接