gpt4 book ai didi

python - R 中的 .csv 数据操作而不是 python

转载 作者:太空宇宙 更新时间:2023-11-03 13:35:09 26 4
gpt4 key购买 nike

我有一个简单的 .csv 格式数据,需要先对其进行操作,然后才能根据该数据创建绘图。但是,我了解如何从 python 操作 .csv 格式数据。我想在 R 中应用相同的逻辑,但我不确定该怎么做。

下面是来自 .csv 文件但加载到 R 中的示例数据。我已经为我们创建了代码来讨论这个问题。

df <- data.frame(Name = c("AC", "AC", "PT", "PT", "OR", "OR"),
useless_column = c("","","A",3,4," "),
measurement = c("H", "", "K", "M", "", "H"),
amount = c(12, 54, 20, 87, 75, 22),
useless_column = c("","","A",3,4," "))

在python中,我一般会这样做:

import csv
import os
import glob
import sys
fileList = glob.glob("R:xxxxxxxxxxxxxxxxxxxxx\*.csv")
for inputFile in fileList:
outputFilename = inputFile + "output.csv"
csvInput = csv.reader(open(inputFile,'r'),delimiter=",")
outputFile = open(outputFilename,'w')
outputFile.write("Name,measurement,amount\n")
csvInput.next()
for line in csvInput:
if line[2] == "H":
meas = "100"
elif line[2] == "K":
meas = "1000"
elif line[2] == "M":
meas = "1000000"
else:
meas = "1"
amount = int(meas) * line[3]

outputFile.write(",".join(line[0],line[2],amount+"\n"]))
outputFile.close()

在 python 中,我可以加载 csv,然后使用 for 循环来识别 csv 文件中的每一行。然后在我继续分析之前定制我的输出文件。从上面看,我希望我的输出类似于下面,并且代码是 R 格式的:

    df <- data.frame(Name = c("AC", "AC", "PT", "PT", "OR", "OR"),
measurment = c("H", "", "K", "M", "", "H"),
amount = c(1200, 54, 20000, 87000000, 75, 2200))

我想知道如何在 R 中执行此操作?我有一个小的 R 代码,请任何人都可以指导我正确的方向:

x <- read.csv("xxxx.csv", header=T,sep=",")
xC = ncol(x)
xR = nrow(x)
op = data.frame(matrix(data = x, nrow= xR, ncol=3,byrow=T))
for (x in :xC)
{
for (r in 1:xR)
{
xxxxxxxx

}

最佳答案

在 R 中调整 python 代码意味着放弃循环以支持矢量化操作。在这里,我们可以根据命名向量创建 meas,然后计算数量:

# dictionnary of measurement values:
m <- c(H = 100, K = 1000, M = 1000000)

# create meas based on measurement
df$meas <- m[df$measurment]
df$meas[is.na(df$meas)] <- 1
# compute amount
df$amount <- df$meas * df$amount

数据

df <- data.frame(Name = c("AC", "AC", "PT", "PT", "OR", "OR"),
measurment = c("H", "", "K", "M", "", "H"),
amount = c(1200, 54, 20000, 87000000, 75, 2200))

关于python - R 中的 .csv 数据操作而不是 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41121379/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com