【问题标题】:Looping and making new column python循环并制作新列python
【发布时间】:2017-10-19 22:02:14
【问题描述】:

我有这个循环

Source= []
for row in df['Num_Col']:
    if row[0:6].isdigit()==True and row[6:8].isalpha()==True:
        Source.append('Num')
        df['Source'] = Source

我想要实现的是,当我遍历指定的列时,我希望它查看前 6 个位置,如果它们是数字,如果最后两个数字是 alpha,那么我希望它将它附加到我的源列表和然后我想创建一个名为:

df['Source'] = Source

这将满足我的 if 语句的要求。我一直收到这个错误

ValueError: Length of values does not match length of index

如果这个新列中的其余列是 Nan 我没关系,我只希望它使用 if 语句指定的参数创建列。我只是不明白为什么它还没有这样做。

     Num_col   Country 
  1  123456HK  Georgia   
  2  273HH123  Georgia
  3  123456HK  Georgia
  4  273HH123  Georgia
  5  123456HK  Georgia

所以当我运行那个循环时,我希望它返回的是这个

     Num_col   Country   Source
  1  123456HK  Georgia   Num
  2  273HH123  Georgia   
  3  123456HK  Georgia   Num
  4  273HH123  Georgia   
  5  123456HK  Georgia   Num

所以基本上只需添加一个名为 source 的列,然后在指定名称为 Num 的列中仅添加与 if 语句匹配的值,该名称是在 if 语句之后指定的。

【问题讨论】:

  • 您可以添加您的数据框和预期输出的概述吗?
  • 是的,我可以,一秒钟。
  • 使用熊猫对吗?

标签: python loops pandas dataframe


【解决方案1】:

您可以使用apply 函数迭代Num_col 列的所有行并应用一个函数。在这种情况下,该函数会检查您指定的条件,并根据条件是否满足返回不同的值。

import numpy as np # for the np.NaN value
df['Source'] = df['Num_col'].apply(lambda nc: 'Num' if nc[0:6].isdigit() and nc[6:8].isalpha() else np.NaN)

# Output:
   Country   Num_col Source
0  Georgia  123456HK    Num
1  Georgia  273HH123    NaN
2  Georgia  123456HK    Num
3  Georgia  273HH123    NaN
4  Georgia  123456HK    Num

【讨论】:

  • 行明智的不是axis=1
  • @DylanMadisetti 如果我在整个数据帧上操作,那么轴会很重要。但是因为我只在子集 df['Num_col'] 上运行 apply,所以我认为轴并不重要
  • 啊,是的。我没看到
【解决方案2】:

我没有测试你的代码,因为我没有数据,但看起来你每次都在尝试设置源。这没有意义,因为Source 数组(顺便说一句,为类保留大写字母)与数据框列大小不匹配。

因此,您应该在构建结束时应用新列。比如:

Source= []
for row in df['Num_Col']:
    if row[0:6].isdigit()==True and row[6:8].isalpha()==True:
        Source.append('Num')
    else:
        Source.append('')

df['Source'] = Source

更好!你可以映射!

def determine_num(row):
    if row[0:6].isdigit()==True and row[6:8].isalpha()==True:
        return 'Num'
    return ''

df['Source'] = df['Num_Col'].apply(determine_num)

完整的函数比 lambda 更易读

【讨论】:

    【解决方案3】:

    最好将numpy.where 与使用indexing with strisdigitisalpha 创建的掩码一起使用:

    mask = df['Num_col'].str[0:6].str.isdigit() & df['Num_col'].str[6:8].str.isalpha()
    df['Source'] = np.where(mask, 'Num', '')
    print (df)
        Num_col  Country Source
    1  123456HK  Georgia    Num
    2  273HH123  Georgia       
    3  123456HK  Georgia    Num
    4  273HH123  Georgia       
    5  123456HK  Georgia    Num
    

    对于nans:

    df.loc[mask, 'Source'] = 'Num'
    print (df)
        Num_col  Country Source
    1  123456HK  Georgia    Num
    2  273HH123  Georgia    NaN
    3  123456HK  Georgia    Num
    4  273HH123  Georgia    NaN
    5  123456HK  Georgia    Num
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多