熊猫:用于将列拆分为2

Eyal S.

我有一个带有列(“位置”)的数据框,其中包含有关城市和州的信息,并用逗号分隔。一些值是无。

我编写了一个函数,将数据分为城市和州,并进行了一些清理:

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

我很难弄清楚如何从此函数创建2个单独的列。如果我使用以下内容:

df['location_info'] = df['location'].apply(split_data)

它将在“ location_info”列中创建一个元组。

在数据框中创建2个新列的最佳方法是什么?一个叫做“ 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

但是如果需要真正使用您的函数(例如更复杂),请添加Series

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章