Python:从String Array中删除np nan值

时间:2018-02-22 18:01:15

标签: python pandas

如何从字符串数组中删除np nan值?

我创建了一个LIST,其中我附加了基于另一个DF的DF中不存在的值。

例如:

NotPresent = [Alan, Susie, nan, nan, nan] 

我希望能够将列表转换为:

NotPresent = [Alan, Susie] 

在Python中处理此问题的最简单方法是什么?

由于

4 个答案:

答案 0 :(得分:3)

如果您的确是['Alan', 'Susie'],那么您可以使用pandas DataFrame

dropna()

其他人已经回答了他们在列表中处理>>> import pandas as pd >>> import numpy as np >>> data = [['Alan'], ['Suzie'], [np.nan], [np.nan]] >>> df = pd.DataFrame(data, columns=['col1']) >>> df col1 0 Alan 1 Suzie 2 NaN 3 NaN >>> df.dropna() col1 0 Alan 1 Suzie 的版本。以下是使用nan

中的nan进行此操作的替代方法
numpy

答案 1 :(得分:2)

您可以使用filter执行此操作:

import numpy as np

NotPresent = ["Alan", "Susie", np.nan, np.nan, np.nan] 

NotPresent = list(filter(lambda i: not i is np.nan, NotPresent))

print(NotPresent)

输出:

['Alan', 'Susie']

答案 2 :(得分:1)

IIUC

[x for x in NotPresent if str(x) != 'nan']
Out[1543]: ['Alan', 'Susie']

答案 3 :(得分:1)

如果nan = np.nan那么:

function submitNegotiation() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss.getSheetByName('Sheet1');
  var negotiationData = ss.getSheetByName('NegotiationData');

  // Sheet1 variables
  var user = sheet1.getRange('Q5').getValue();
  var storyId = Number(sheet1.getRange('R6').getValue().split("-")[1]);
  var estimateNum = sheet1.getRange('Q6').getValue();
  var note = sheet1.getRange('Q7').getValue();
  var pointers = [storyId, estimateNum, note];

  // NegotiationData variables
  var range = negotiationData.getDataRange().getValues();
  var columns = negotiationData.getLastColumn();  
  var users = negotiationData.getRange(1, 1, 1, columns).getValues();


  for(var i = 0; i < columns; i++) {

    // match user with users to get column number
    if(users[0][i] == user) {
      var col = negotiationData.getRange(1, i + 1).getColumn();

      // count rows in col
      var rowCount = 1;
      for(var i = 1; i < range.length; i++) {
        if (range[i][col - 1] != "") {
          rowCount++;
        }
      }

      // assign pointers
      var newRow = rowCount + 1;
      for(var j = 0; j < pointers.length; j++) {
        negotiationData.getRange(newRow, col, 1, 1).setValue(pointers[j]);
        col++;
      }
    }
  }
}

输出将是:

import numpy as np import math NotPresent = ["Alan", "Susie", np.nan, np.nan, np.nan] print(NotPresent) n = len(NotPresent) j = -1 for i in range(n): j += 1 if not isinstance(NotPresent[j], str) and math.isnan(NotPresent[j]): del NotPresent[j] j = j-1 print(NotPresent)

['Alan', 'Susie', nan, nan, nan]

如果&#34; nan&#34;是一个字符串然后:

['Alan', 'Susie']

输出将是:

NotPresent = ["Alan", "Susie", "nan", "nan", "nan"] print(NotPresent) n = len(NotPresent) j = -1 for i in range(n): j += 1 if NotPresent[j] == "nan": del NotPresent[j] j -= 1 print(NotPresent)

['Alan', 'Susie', "nan", "nan", "nan"]