【问题标题】:How to loop through pandas dataframe, check conditions, perform string manipulations & write to a new column?如何遍历 pandas 数据框、检查条件、执行字符串操作和写入新列?
【发布时间】: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 中的值并不像预期的那样,如下所示。 另外,我收到这样的警告 "ma​​in: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


【解决方案1】:

在您的情况下,我建议使用loc 创建一个新列。

文档:loc

文档:str expand

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'

刚刚看到预期的输出。阅读我链接的文档并根据需要更改str.extract。

【讨论】:

  • 谢谢希德。但对不起,我不明白提取部分。所以我现在用 split 修改了你的代码,它起作用了。 df.loc[df['Col1']==1,'Col3'] = df['Col2'].str.split('|').str.get(0) df.loc[df['Col1' ]==0,'Col3'] = '不适用'
  • @Simbu 看到我上面的答案。正则表达式模式是从字符串中准确提取所需内容的好方法。
【解决方案2】:

我觉得你可以的

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 2022-01-14
    • 2017-10-05
    相关资源
    最近更新 更多