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

时间:2016-02-22 11:50:19

标签: python 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']

我想在此数据框中添加新列,其中第一个数字来自“First”列中的值: a)将数字从“First”列更改为字符串 b)从新创建的字符串中提取第一个字符 c)b的结果保存为数据框中的新列

我不知道如何将它应用于pandas数据框对象。我很感激能帮助我。

2 个答案:

答案 0 :(得分:44)

将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)

答案 1 :(得分:0)

.str.get

这是最简单的指定字符串方法

# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df

        A    B
0     xyz  123
1     abc  456
2  foobar  789

df.dtypes

A    object
B     int64
dtype: object

对于字符串(读取:object)类型的列,请使用

df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)

.str通过返回NaN作为输出来处理NaN。

对于非数字列,需要事先进行.astype转换,如@Ed Chum的答案所示。

# Note that this won't work well if the data has NaNs. 
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

列表理解和索引

enough evidence建议您在这里进行简单的列表理解会更好,并且可能会更快。

# For string columns
df['C'] = [x[0] for x in df['A']]

# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

如果您的数据具有NaN,那么您需要使用列表理解中的if / else来适当地处理此问题,

df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2

        A      B
0     xyz  123.0
1     NaN  456.0
2  foobar    NaN

# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]

# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]

        A      B    C    D
0     xyz  123.0    x    1
1     NaN  456.0  NaN    4
2  foobar    NaN    f  NaN

让我们对一些较大的数据进行一些时间测试。

df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True) 

%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])

%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])

12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

列表理解速度提高了4倍。