我有一個df: col10 011392902010011 011392901010012 011392902010023 011392901010024 011392902010035 011392901010036 011392902010047 011393101010018 011392902010059 01139290301001 ... 5908 01139?ê210205909 01139?ê210135910 01139?ê110085911 01139?ê210115912 01139?ê03003在int唯一的情況下,我需要將前7個數(shù)字提取到新列中;在包含字符的情況下,我需要將前5和8,9個數(shù)字提取到新列中。我將這段代碼嘗試到一個組成的數(shù)據(jù)幀上,嘗試解決該問題的方法,它可以工作,但是當(dāng)我在實(shí)際數(shù)據(jù)集上嘗試它時,它并沒有按預(yù)期工作,主要原因是我的實(shí)際數(shù)據(jù)中df有整數(shù),并且對他們。df['col2']=df[col1][0:5]+df['col1'][8]0 01139290201001011392902010051 01139290101001011392902010052 01139290201002011392902010053 01139290101002011392902010054 01139290201003011392902010055 NaN6 NaN7 NaN8 NaN9 NaN還為什么會導(dǎo)致NaN值?我希望它看起來像這樣: 01139290201001 to 0113929 for integer only rows and like this for the others 01139?ê03003 to 0113903
1 回答

Cats萌萌
TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個贊
使用 .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
添加回答
舉報(bào)
0/150
提交
取消