我有一个名为car
的数据框,我想创建一个新的列“Brand”,它是列数据“name”的第一个单词
输入数据帧:
mpg cylinders displacement horsepower weight name
0 18.0 8 307.0 130.0 chevrolet chevelle malibu
1 15.0 8 350.0 165.0 buick skylark 320
2 18.0 8 318.0 150.0 plymouth satellite
3 16.0 8 304.0 150.0 amc rebel sst
4 17.0 8 302.0 140.0 ford torino
首先,我找到第一个单词的结尾:
cars['brandno'] = cars['name'].str.find(' ')
然后我用brandno
将单词切分如下:
cars['brand'] = cars['name'].str[:'brandno']
结果:
mpg cylinders displacement horsepower weight name brand brandno
0 18.0 8 307.0 130.0 chevrolet chevelle malibu NaN 9.0
1 15.0 8 350.0 165.0 buick skylark 320 NaN 5.0
2 18.0 8 318.0 150.0 plymouth satellite NaN 8.0
3 16.0 8 304.0 150.0 amc rebel sst NaN 3.0
4 17.0 8 302.0 140.0 ford torino NaN 4.0
但是,从reuslt中可以看出,它不起作用。我怎样才能解决这个问题
您只需使用pd.Series.apply()即可
以下内容可能适用于您:
相关问题 更多 >
编程相关推荐