【问题标题】:Replacing missing values and strings with 0 and values用 0 和值替换缺失值和字符串
【发布时间】:2015-08-18 20:43:27
【问题描述】:

我有一个缺少值的数据框。如何编写 python 或 R 代码来用 0 替换空格,用 1 替换单个字符串,以及由“\t”连接的多个字符串,其数字对应于多少个“\t”s + 1。

我的数据框:

        col1    col2    col3
row1    5blue   2green5 white
row2            white   green\twhite3\t3blue5
row3    blue3           white
row4    7blue   green2  
row5            3green  3white6
row6    6blue   green\t6white7  green   
row7    5blue5  6green  white
row8    blue6

预期输出:

        col1    col2    col3
row1    1   1   1
row2    0   1   3
row3    1   0   1
row4    1   1   0   
row5    0   1   1
row6    1   2   1   
row7    1   1   1
row8    1   0   0   

有什么想法吗?谢谢

【问题讨论】:

  • 你的分隔符是什么?空间?这就是它的样子。该数据框是文本文件的一部分吗?
  • 数据框是文件的一部分吗?
  • 是的,从 csv 文件中读取。

标签: python r string replace


【解决方案1】:

我正在使用一个函数来检查每个列元素并检查该元素是否为空格(您可以根据自己拥有的内容进行更改。它对我来说看起来像一个空格),如果是则返回 0,否则它用 "\t" 分割字符串并计算产生的字符串。

# example dataset
dt = data.frame(col1 = c("green\twhite3\t3blue5","green"),
                col2 = c(" ", "green\twhite3"), stringsAsFactors = F)

dt

#                   col1         col2
# 1 green\twhite3\t3blue5             
# 2               green green\twhite3


ff = function(x) 
{
  res = vector()                                                             # create an empty vector to store counts for each element
  for (i in 1:length(x)){                                                    # iterate through each element
        res[i] = ifelse(x[i]==" ", 0, length(unlist(strsplit(x[i],"\t"))))   # if the element is space return 0, else split string by \t and count new strings
                        }
  return(res)                                                                # return the stored values
}


data.frame(sapply(dt, function(x) ff(x)))                                    # apply the function to all columns and save it as a data.frame

#     col1 col2
# 1    3    0
# 2    1    2

【讨论】:

  • 您的 R 代码非常适合我。感谢您的帮助。
  • 乐于助人。如果您将来发现任何限制,请告诉我,我会更新它。
【解决方案2】:

Parsing Tab Delimited

阅读上面的这篇文章。它涵盖了使用 python csv 模块来解析制表符分隔。我想它会对你有所帮助。

输入文件 data_frame.txt

5blue   2green5 white
    white   green\twhite3\t3blue5
blue3       white
7blue   green2  
    3green  3white6
6blue   green\t6white7  green
5blue5  6green  white

下面的代码

import csv

data_frame = open('data_frame.txt','r')             ## create input file for dataframe
output_matrix = []                                  ## output matrix
reader = csv.reader(data_frame, dialect="excel-tab")  ## Setup tab delimter file

for line in reader:                                 ## Read each line in the data frame
    out_line = []                                   ## Setup temp out-line var
    for item in line:

        if item == '':                              ## If item in line is null then put zero
            out_line.append(0)
        elif r"""\t""" in item:                     ## if item in line contains a "\t" character then put count + 1
            out_line.append(item.count(r"""\t""")+1)
        else:                                       ## Else item is 1
            out_line.append(1)
    output_matrix.append(out_line)                  ## Append line into output matrix

for line in output_matrix:
     print line                     ## Print output matrix

此代码应该可以工作...您只需将 output_matrix 输出到 csv 文件即可。

输出

[1, 1, 1]
[0, 1, 3]
[1, 0, 1]
[1, 1, 0]
[0, 1, 1]
[1, 2, 1]
[1, 1, 1]

【讨论】:

  • 如果行和列标题存在于您的 csv 文件中,只需删除它们即可。否则,您可以修改我的代码以合并它们。
  • 简单的python代码!非常感谢@budder。我获得了更多关于如何处理这种情况的python知识。
【解决方案3】:

使用yourstring.count("\t")函数获取制表符个数,数值加1得到字数。如果字符串为空,则输出 0。

【讨论】:

  • 感谢@Sylver 提供的信息
猜你喜欢
  • 1970-01-01
  • 2020-12-03
  • 2021-11-30
  • 2013-07-22
  • 2013-11-04
  • 1970-01-01
  • 2020-01-04
相关资源
最近更新 更多