我试图将一列一分为二,但我知道我的数据中有空值。想象一下这个数据帧:df = pd.DataFrame(['fruit: apple','vegetable: asparagus',None, 'fruit: pear'], columns = ['text'])
df
text
0 fruit: apple
1 vegetable: asparagus
2 None
3 fruit: pear
我想把它分成多个列,如下所示:df['cat'] = df['text'].apply(lambda x: 'unknown' if x == None else x.split(': ')[0])
df['value'] = df['text'].apply(lambda x: 'unknown' if x == None else x.split(': ')[1])
print df
text cat value
0 fruit: apple fruit apple
1 vegetable: asparagus vegetable asparagus
2 None unknown unknown
3 fruit: pear fruit pear
但是,如果我有以下df:df = pd.DataFrame(['fruit: apple','vegetable: asparagus',np.nan, 'fruit: pear'], columns &#