我有一个名为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中所看到的,它不起作用。我该如何解决这个问题呢?
发布于 2021-02-23 23:48:03
您可以简单地使用pd.Series.apply()
cars['brandno'] = cars['name'].apply(lambda x: x.split(" ")[0])
# This should make a new column having only the first name of the cars发布于 2021-02-23 23:55:58
以下可能适用于您:
cars['brand'] = cars.name.str.split(expand=True)[0]https://stackoverflow.com/questions/66336227
复制相似问题