从列中获取字符串的第一个字母 [英] Get first letter of a string from column
问题描述
我正在和熊猫打架,现在我正在失去.我有与此类似的源表:
I'm fighting with pandas and for now I'm loosing. I have source table similar to this:
import pandas as pd
a=pd.Series([123,22,32,453,45,453,56])
b=pd.Series([234,4353,355,453,345,453,56])
df=pd.concat([a, b], axis=1)
df.columns=['First', 'Second']
我想从列"First"中的值的第一位向该数据帧添加新列: a)将数字从第一"列更改为字符串 b)从新创建的字符串中提取第一个字符 c)来自b的结果另存为数据框中的新列
I would like to add new column to this data frame with first digit from values in column 'First': a) change number to string from column 'First' b) extracting first character from newly created string c) Results from b save as new column in data frame
我不知道如何将其应用于熊猫数据框对象.我将非常感谢您对此的帮助.
I don't know how to apply this to the pandas data frame object. I would be grateful for helping me with that.
推荐答案
将col的dtype
投射到str
,您可以执行矢量化切片调用str
:
Cast the dtype
of the col to str
and you can perform vectorised slicing calling str
:
In [29]:
df['new_col'] = df['First'].astype(str).str[0]
df
Out[29]:
First Second new_col
0 123 234 1
1 22 4353 2
2 32 355 3
3 453 453 4
4 45 345 4
5 453 453 4
6 56 56 5
如果需要,可以再次在列上调用astype(int)
来回退dtype
if you need to you can cast the dtype
back again calling astype(int)
on the column
这篇关于从列中获取字符串的第一个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!