Pandas make new column from string slice of another column
我想在Pandas中使用为数据帧中的另一列切片的字符串创建一个新列。
例如。
1 2 3 | Sample Value New_sample AAB 23 A BAB 25 B |
其中
我尝试了许多尝试都无济于事-我觉得我缺少一些简单的东西。
最有效的方法是什么?
您可以调用
1 | df['New_Sample'] = df.Sample.str[:1] |
您也可以在df上调用lambda函数,但这在较大的数据帧上会比较慢:
1 2 3 4 5 6 7 8 | In [187]: df['New_Sample'] = df.Sample.apply(lambda x: x[:1]) df Out[187]: Sample Value New_Sample 0 AAB 23 A 1 BAB 25 B |
您还可以使用
1 | df['New_sample'] = df['Sample'].str.slice(0,1) |
从熊猫文档中:
Series.str.slice(start=None, stop=None, step=None)
Slice substrings from each element in the Series/Index
blockquote>
对于切片索引(如果索引是字符串类型),可以尝试:
1 df.index = df.index.str.slice(0,1)