用0和值替换缺少的值和字符串

2024-05-17 15:56:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个缺少值的数据帧。我如何编写python或R代码来将空格替换为0,将单个字符串替换为1,并将多个由“\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

预期输出:

^{pr2}$

有什么想法吗?谢谢


Tags: 数据字符串代码数量数字greencol2col3
3条回答

使用yourstring.count("\t")函数来获得制表符的数量,将1加到值中就可以得到单词的数量。如果字符串为空,则输出0。在

我使用了一个函数,该函数将访问每个column元素并检查元素是否为一个空格(您可以根据所拥有的内容更改该元素)。它在我看来像一个空格),如果是,则返回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

Parsing Tab Delimited

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

输入文件数据_帧.txt

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

下面的代码

^{pr2}$

这个代码应该可以工作。。。您只需将输出矩阵输出到csv文件。在

输出

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

相关问题 更多 >