python - 按 Pandas 中的位置提取数字?

标签 python pandas

我有一个 df:

                  col1
0       01139290201001
1       01139290101001
2       01139290201002
3       01139290101002
4       01139290201003
5       01139290101003
6       01139290201004
7       01139310101001
8       01139290201005
9       01139290301001
            ...      
5908      01139ÅÊ21020
5909      01139ÅÊ21013
5910      01139ÅÊ11008
5911      01139ÅÊ21011
5912      01139ÅÊ03003

我需要将仅 int 情况下的前 7 个数字提取到新列,以及包含字符的情况下的前 5 和 8,9 数字。

我在一个组成的数据帧中尝试了这段代码,尝试解决它的方法,它起作用了,但是当我在实际数据集上尝试它时,它没有按预期工作,主要原因是我的实际 df 有整数并且对它们进行了计算。

df['col2']=df[col1][0:5]+df['col1'][8]


0       0113929020100101139290201005
1       0113929010100101139290201005
2       0113929020100201139290201005
3       0113929010100201139290201005
4       0113929020100301139290201005
5                                NaN
6                                NaN
7                                NaN
8                                NaN
9                                NaN

为什么它会导致 NaN 值?

我希望它看起来像这样:

 01139290201001 to 0113929 for integer only rows and like this for the others
 01139ÅÊ03003 to 0113903

最佳答案

使用.apply

例如:

import pandas as pd
df = pd.DataFrame({"col1": ["01139290201001", "01139290101001", "01139290201002", "01139ÅÊ21020", "01139ÅÊ21013", "01139ÅÊ11008"]})
df["col2"] = df["col1"].apply(lambda x: x[:7] if x.isdigit() else x[:5]+x[9:11] )
print(df)

输出:

             col1     col2
0  01139290201001  0113929
1  01139290101001  0113929
2  01139290201002  0113929
3    01139ÅÊ21020  0113921
4    01139ÅÊ21013  0113921
5    01139ÅÊ11008  0113911

关于python - 按 Pandas 中的位置提取数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50982565/

相关文章:

Python Mock Patch 一个类中的多个方法

python - 按两列中的值对 NumPy 数组进行排序

python - 将 Pandas 数据框列传递给 NLTK 分词器

python - 列表的列,将列表转换为字符串作为新列

python - 安装 pandas 包时出错 : no module named numpy

python - 如何使用多个 Tkinter 复选按钮对齐列?

python - Django ModelChoiceField 没有加号按钮

python - 保留一列的首选值并删除不太首选的值

python - 在 Python 中绘制直方图的时间序列

python - 在不使用 for 循环的情况下从列表中访问类变量?