【发布时间】:2019-10-01 19:35:13
【问题描述】:
我有一个如下所示的数据框;
--------------------------------
Col1 Col2
--------------------------------
1 AppVer: 1.1.1 | name: A
0 name:B
1 AppVer: 2.3.1 | name: B
我想根据条件创建一个新列 (newCol3) 1.如果Col1=1,则根据“|”拆分Col2并写入列 newCol3 2. 如果 Col1=0 则在 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 中的切片副本上设置值。 尝试改用 .loc[row_indexer,col_indexer] = value 请参阅文档中的注意事项:http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy"
获得的输出:
---------------------------------------------------
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
向我提供任何帮助/建议。
【问题讨论】:
-
为什么看起来你的 if 语句是倒退的?如果 Col1 == 1,您不应该拆分值吗?
-
应该是 np.where 吗?
标签: python string pandas loops conditional