我有一个类似下面的数据框架;
--------------------------------
Col1 Col2
--------------------------------
1 AppVer: 1.1.1 | name: A
0 name:B
1 AppVer: 2.3.1 | name: B
我想根据条件1创建一个新列( newCol3 )。如果是Col1=1,则根据"|“拆分Col2并写入列newCol3 2。如果是Col1=0,则将"Not a”写入列newCol3
我尝试了以下使用iterrows和条件语句的循环代码;
for index, row in df1.iterrows():
if row['Col1']==1:
df1['newCol3']="NA"
elif row['Col1']==0:
a=row['Col2'].split("|")
df1['newCol3']=a[0]
但是,newCol3中的值并不像下面所示的那样。此外,我还收到类似以下"main:8: SettingWithCopyWarning的警告:正在尝试对来自DataFrame的切片的副本设置值。请尝试使用.locrow_indexer,col_indexer = value,请参阅文档中的警告:“
获取的输出:
---------------------------------------------------
Col1 Col2 newCol3
---------------------------------------------------
1 AppVer: 1.1.1 | name: A 1.1.1
0 name:B 1.1.1
1 AppVer: 2.3.1 | name: B 2.3.1
预期输出:
---------------------------------------------------
Col1 Col2 newCol3
---------------------------------------------------
1 AppVer: 1.1.1 | name: A 1.1.1
0 name:B Not Applicable
1 AppVer: 2.3.1 | name: B 2.3.1
向我提供任何帮助/建议。
发布于 2019-05-15 02:09:55
在您的例子中,我建议使用loc
创建一个新列。
文档:loc
文档:str expand
用于字符串提取的文档:str.extract
df.loc[df['Col1']==1,'Col3'] = df['Col2'].str.extract(pat='insert the pattern here')
df.loc[df['Col1']==0,'Col3'] = 'Not Applicable'
刚刚看到了预期的输出。阅读我链接的文档,并根据需要更改str.extract
。
发布于 2019-05-15 02:12:19
我觉得你能做到
df['New']=df.Col2.str.extract('(\d*\.?\d+\.?\d+)').fillna('Not Applicable')
df
Out[43]:
Col1 Col2 New
0 1 AppVer: 1.1.1 | name: A 1.1.1
1 0 name:B Not Applicable
2 1 AppVer: 2.3.1 | name: B 2.3.1
https://stackoverflow.com/questions/56136099
复制相似问题