我有一个带有列(“location”)的数据框,该列包含由逗号分隔的城市和州的信息。有些值不是。
我写了一个函数,将数据分为城市和州,并对其进行一些清理:

def split_data(x):
    if x:
        s = x.split(',')
        city = s[0].lstrip().rstrip()
        state = s[1].lstrip().rstrip()
    else:
        city = None
        state = None
    return city, state

我很难弄清楚如何从这个函数创建两个独立的列。
如果我使用以下选项:
df['location_info'] = df['location'].apply(split_data)

它在“location_info”列中创建一个元组。
在dataframe中创建两个新列的最佳方法是什么?一个称为“city”,另一个称为“state”?

最佳答案

我认为您可以使用向量化函数str.splitstr.strip

df[['city','state']]=df['location'].str.split(',',expand=True).apply(lambda x: x.str.strip())

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

样品:
df = pd.DataFrame({'location':[' a,h ',' t ,u', None]})
print (df)
  location
0     a,h
1     t ,u
2     None

df[['city','state']]=df['location'].str.split(',',expand=True).apply(lambda x: x.str.strip())
print (df)
  location  city state
0     a,h      a     h
1     t ,u     t     u
2     None  None  None

但如果真的需要使用您的函数(例如更复杂),请添加:
def split_data(x):
    if x:
        s = x.split(',')
        city = s[0].strip()
        state = s[1].strip()
    else:
        city = None
        state = None
    return pd.Series([city, state], index=['city','state'])

df[['city','state']] = df['location'].apply(split_data)
print (df)
  location  city state
0     a,h      a     h
1     t ,u     t     u
2     None  None  None

关于python - Pandas :用于将列拆分为2,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44173155/

10-12 21:27