PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label rows. Show all posts
Showing posts with label rows. Show all posts

Friday, October 7, 2022

[FIXED] How to eleminate variables based on comparison of specific rows

 October 07, 2022     r, rows, statistics     No comments   

Issue

I have data that contains twelve rows and more than 500 variables I want to keep only the variables that have value of line 9 > 5* value of line 10

Example of data:

       Name   ClassType    Col1   Col2   Col3     
       ---------------------------------------
        A      Class1       10     50    12        
        B      Class2        7     20    12
        C      Class1        8     12     8
        D      Class1        9     14    17
        E      Class2        3     15    14
        F      Class2       10     15    16
        G      Class2       12     22    15
        H      Class1       10     28    10
        I       NA          50     10    30
        J       NA           8      5     2

Result I want: delete of column 2 because the value of line 9 in that column is < 5* value of line 10 of the same column:

      Name   ClassType    Col1   Col3     
      -------------------------------
        A      Class1       10    12        
        B      Class2        7    12
        C      Class1        8     8
        D      Class1        9    17
        E      Class2        3    14
        F      Class2       10    16
        G      Class2       12    15
        H      Class1       10    10
        I       NA          50    30
        J       NA           8     2

I tried if condition but it didn't give me good results, but I want to know if there's any other way.

The code i tried

data_4 <- as.data.frame(data_3[,1, drop=FALSE])


for (i in 2:640) {
  a = as.numeric(data_3[9,i])
  b = as.numeric(data_3[10,i])
  print(b)
  c = as.numeric(b*5)
  
  if(a > c) {
    data_4 <- cbind(data_4[, , drop=FALSE], data_3[ ,i,drop=FALSE])
    
    
  }

Thank you


Solution

We may use select to select the character columns and the numeric columns where the condition matches - 9th element of the column is greater than 5 times the last value

library(dplyr)
df1 <- df1 %>% 
  dplyr::select(where(is.character),
       where(~ is.numeric(.x) && nth(., 9) >  5 * last(.) ))

-output

df1
    Name ClassType Col1 Col3
1     A    Class1   10   12
2     B    Class2    7   12
3     C    Class1    8    8
4     D    Class1    9   17
5     E    Class2    3   14
6     F    Class2   10   16
7     G    Class2   12   15
8     H    Class1   10   10
9     I      <NA>   50   30
10    J      <NA>    8    2

data

df1 <- structure(list(Name = c("A", "B", "C", "D", "E", "F", "G", "H", 
"I", "J"), ClassType = c("Class1", "Class2", "Class1", "Class1", 
"Class2", "Class2", "Class2", "Class1", NA, NA), Col1 = c(10L, 
7L, 8L, 9L, 3L, 10L, 12L, 10L, 50L, 8L), Col2 = c(50L, 20L, 12L, 
14L, 15L, 15L, 22L, 28L, 10L, 5L), Col3 = c(12L, 12L, 8L, 17L, 
14L, 16L, 15L, 10L, 30L, 2L)), class = "data.frame", row.names = c(NA, 
-10L))


Answered By - akrun
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, August 29, 2022

[FIXED] how do i get 5 random rows from a list

 August 29, 2022     csv, list, python, random, rows     No comments   

Issue

I'm pretty new to python, and my problem is, I'm trying to get 5 random rows from a list with a user input value condition, i get all the values from a chosen category and supposed to get only 5 rows from that randomly.

I've tried various solutions but it doesn't help me anyway sry for my english

here's the code:

import csv import random

with open("pontos.csv","r")as f:
    r=csv.reader(f,delimiter=",")
    l=list(r)
    
    
    def ex1():
    #ex1
        for x in l:
            val=x[1],x[5]
            print(':'" ".join(val),"\n")
    

    def ex2():
        #ex2
        # escolhe cultura
            val = input("Cat:\n").split(",")

            for row in l:
                if all([x in row for x in val]):
                    print(','.join(row),"\n")
    
    def ex3():
        n=4
    # print("categorias:\n Desporto,cultura,História,Paisagem,Praia,Gastronomia,Natureza,Natureza")
        # escolhe cultura
        val = input("Cat:\n").split(",")
        for row in l:
                if all(x in row for x in val):
                    print(row)
                    
def main():
    while True:
        escolha=int(input("Menu:\n 1-mostrar todos os locais \n 2-Mostrar todos os locais de uma categoria \n 3- mostrar locais de uma categoria ao acaso \n 4-Sair \n Escolha: "))
        if escolha==1:
            ex1()
        if escolha ==2:
            ex2()
        if escolha==3:
            ex3()
            if escolha== 4:
                break
        else:
            print("escolha invalida")

main()

note: its on ex3


Solution

you can use random.sample for select a random row (item) from a list. in main function your if escolha== 4: no effect because inside "if escolha==3:".

import csv
import random


with open("open_position.csv", "r") as f:
    r = csv.reader(f, delimiter=",")
    l = list(r)


def ex1():
    # ex1
    # used random.sample(list, number_sample)
    for x in random.sample(l, 5):
        val = x[1], x[5]
        print(':'" ".join(val), "\n")


def ex2():
    # ex2
    # escolhe cultura
    val = input("Cat:\n").split(",")

    # used random.sample(list, number_sample)
    for row in random.sample(l, 5):
        if all([x in row for x in val]):
            print(','.join(row), "\n")


def ex3():
    n = 4
    # print("categorias:\n Desporto,cultura,História,Paisagem,Praia,Gastronomia,Natureza,Natureza")
    # escolhe cultura
    val = input("Cat:\n").split(",")
    # used random.sample(list, number_sample)
    for row in random.sample(l, 5):
        if all(x in row for x in val):
            print(row)


def main():
    while True:
        escolha = int(input(
            "Menu:\n 1-mostrar todos os locais \n 2-Mostrar todos os locais de uma categoria \n 3- mostrar locais de uma categoria ao acaso \n 4-Sair \n Escolha: "))
        if escolha == 1:
            ex1()
        if escolha == 2:
            ex2()
        if escolha == 3:
            ex3()
            # this is incorrect
            # if escolha == 4:
            #     break
        if escolha == 4:
            break
        else:
            print("escolha invalida")


main()


Answered By - ali
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, May 13, 2022

[FIXED] How to append rows to an R data frame

 May 13, 2022     append, dataframe, merge, r, rows     No comments   

Issue

I have looked around StackOverflow, but I cannot find a solution specific to my problem, which involves appending rows to an R data frame.

I am initializing an empty 2-column data frame, as follows.

df = data.frame(x = numeric(), y = character())

Then, my goal is to iterate through a list of values and, in each iteration, append a value to the end of the list. I started with the following code.

for (i in 1:10) {
    df$x = rbind(df$x, i)
    df$y = rbind(df$y, toString(i))
}

I also attempted the functions c, append, and merge without success. Please let me know if you have any suggestions.

Update from comment: I don't presume to know how R was meant to be used, but I wanted to ignore the additional line of code that would be required to update the indices on every iteration and I cannot easily preallocate the size of the data frame because I don't know how many rows it will ultimately take. Remember that the above is merely a toy example meant to be reproducible. Either way, thanks for your suggestion!


Solution

Update

Not knowing what you are trying to do, I'll share one more suggestion: Preallocate vectors of the type you want for each column, insert values into those vectors, and then, at the end, create your data.frame.

Continuing with Julian's f3 (a preallocated data.frame) as the fastest option so far, defined as:

# pre-allocate space
f3 <- function(n){
  df <- data.frame(x = numeric(n), y = character(n), stringsAsFactors = FALSE)
  for(i in 1:n){
    df$x[i] <- i
    df$y[i] <- toString(i)
  }
  df
}

Here's a similar approach, but one where the data.frame is created as the last step.

# Use preallocated vectors
f4 <- function(n) {
  x <- numeric(n)
  y <- character(n)
  for (i in 1:n) {
    x[i] <- i
    y[i] <- i
  }
  data.frame(x, y, stringsAsFactors=FALSE)
}

microbenchmark from the "microbenchmark" package will give us more comprehensive insight than system.time:

library(microbenchmark)
microbenchmark(f1(1000), f3(1000), f4(1000), times = 5)
# Unit: milliseconds
#      expr         min          lq      median         uq         max neval
#  f1(1000) 1024.539618 1029.693877 1045.972666 1055.25931 1112.769176     5
#  f3(1000)  149.417636  150.529011  150.827393  151.02230  160.637845     5
#  f4(1000)    7.872647    7.892395    7.901151    7.95077    8.049581     5

f1() (the approach below) is incredibly inefficient because of how often it calls data.frame and because growing objects that way is generally slow in R. f3() is much improved due to preallocation, but the data.frame structure itself might be part of the bottleneck here. f4() tries to bypass that bottleneck without compromising the approach you want to take.


Original answer

This is really not a good idea, but if you wanted to do it this way, I guess you can try:

for (i in 1:10) {
  df <- rbind(df, data.frame(x = i, y = toString(i)))
}

Note that in your code, there is one other problem:

  • You should use stringsAsFactors if you want the characters to not get converted to factors. Use: df = data.frame(x = numeric(), y = character(), stringsAsFactors = FALSE)


Answered By - A5C1D2H2I1M1N2O1R2T1
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing