[英]How to loop through pandas dataframe, check conditions, perform string manipulations & write to a new column?
I have a dataframe like below; 我有一个如下数据框;
--------------------------------
Col1 Col2
--------------------------------
1 AppVer: 1.1.1 | name: A
0 name:B
1 AppVer: 2.3.1 | name: B
I wanted to create a new column (newCol3) based on the condition 1. If Col1=1 then split the Col2 based on "|" 我想根据条件1创建一个新列(newCol3)。如果Col1 = 1,则根据“|”拆分Col2 and write to the column newCol3 2. If Col1=0 then write "Not Applicable" to the column newCol3 并写入newCol3列2.如果Col1 = 0,则将“Not Applicable”写入newCol3列
I tried the below code for loop using iterrows & conditional statements; 我使用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]
But i the value in newCol3 is not as expected as shown below. 但我在newCol3中的值不如预期,如下所示。 Also, i get a warning like this " main :8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy " 另外,我得到一个像这样的警告“ main :8:SettingWithCopyWarning:尝试在DataFrame的切片副本上设置一个值。尝试使用.loc [row_indexer,col_indexer] = value请参阅文档中的警告: http : //pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy “
Obtained Output: 获得的输出:
---------------------------------------------------
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
Expected Output: 预期产出:
---------------------------------------------------
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
Provide me any help/suggestions. 向我提供任何帮助/建议。
In your case I would suggest using loc
to create a new column. 在你的情况下,我建议使用loc
来创建一个新列。
Docs: str expand Docs: str扩展
Docs for str extract: str.extract str提取的文档: 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'
Just saw the expected output. 刚看到预期的输出。 Read the docs I linked and change the str.extract
as required. 阅读我链接的文档并根据需要更改str.extract
。
I feel like you can do 我觉得你能做到
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.