我正在和 Pandas 打架,现在我输了。我有类似这样的源表:
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']
我想在此数据框中添加新列,其中第一个数字来自“第一”列中的值: a) 将数字从“First”列更改为字符串 b) 从新创建的字符串中提取第一个字符 c) 来自 b 的结果另存为数据框中的新列
我不知道如何将其应用于 pandas 数据框对象。如果能帮我解决这个问题,我将不胜感激。
最佳答案
将col的dtype
转换成str
,就可以调用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
如果您需要,您可以将 dtype
再次转换回来,在列上调用 astype(int)
关于python - 从列中获取字符串的第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35552874/