我有一个格式为的数据框(df):
name alias col3
mark david ['3109892828','email@john.com','123 main st']
john twixt ['5468392873','email@twix.com','345 grand st']
将col3拆分为新的命名列的简洁方法是什么? (也许使用lambda并申请)
答案 0 :(得分:2)
您可以对列表元素应用连接以创建逗号分隔字符串,然后使用expand=True
调用矢量化str.split
以创建新列:
In [12]:
df[['UserID', 'email', 'address']] = df['col3'].apply(','.join).str.split(expand=True)
df
Out[12]:
alias col3 name \
0 david [3109892828, email@john.com, 123 main st] mark
1 twixt [5468392873, email@twix.com, 345 grand st] john
UserID email address
0 3109892828,email@john.com,123 main st
1 5468392873,email@twix.com,345 grand st
更简洁的方法是应用pd.Series
ctor,它会将每个列表变成一个系列:
In [15]:
df[['UserID', 'email', 'address']] = df['col3'].apply(pd.Series)
df
Out[15]:
alias col3 name UserID \
0 david [3109892828, email@john.com, 123 main st] mark 3109892828
1 twixt [5468392873, email@twix.com, 345 grand st] john 5468392873
email address
0 email@john.com 123 main st
1 email@twix.com 345 grand st
答案 1 :(得分:0)
这是我想出的。它包括对原始文件进行一些清理,以及转换为字典。
import pandas as pd
with open('/path/to/file', 'rb') as f:
data = f.readlines()
data = map(lambda x: x.split('}'), data)
data_df = pd.DataFrame(data)
data_dfn = data_df.transpose()
data_new = data_dfn[0].map(lambda x: x.lstrip('[,{)').replace("'","").split(','))
s = pd.DataFrame(data_new)
d = dict(data_new)
D = pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in d.iteritems() ]))
D = D.transpose()