如何对数据帧中的每个变量进行切片?

2024-10-01 00:19:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为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中可以看出,它不起作用。我怎样才能解决这个问题


Tags: 数据namenan单词carsweightmpgdisplacement
2条回答

您只需使用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

以下内容可能适用于您:

cars['brand'] = cars.name.str.split(expand=True)[0]

相关问题 更多 >