python - 从列中获取字符串的第一个字母

标签 python pandas

我正在和 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/

相关文章:

python - 日期范围 : is there a more pythonic way? 中的所有星期二和星期三

python - 将 Pandas 数据框中的两列分成两列并命名

python - 日期时间索引KeyError : 'the label [2000-01-03 00:00:00] is not in the [index]'

python - 根据用户输入绘制特定列

python - 在python中添加两个datetime.datetime.strptime().time()对象

python - 并行化Python列表理解并没有提高性能

python - 通过将列表或字符串的列与另一个列表匹配来进行分组并创建新的数据框

python - Pandas DataFrame 将 json 列列表转换为信息行,每 "id"

python - TimedRotatingFileHandler 日志的文件名约定? (Python)

python - 通过 join 获取所有字段。 Django