[英]How do I apply an Excel formula to the values in an entire column?
I am trying to parse file names in a folder and figured out how to load them into a csv file but I need to apply a formula to the column in order to get my final results. 我试图解析文件夹中的文件名,并弄清楚如何将它们加载到csv文件中,但是我需要对列应用公式才能获得最终结果。 The code and data is as follows along with the Excel formula I plan on using.
代码和数据以及我计划使用的Excel公式如下。
This snippet of code takes the file names from the folder "testfolder" and dumps them in the csv file. 此代码段从文件夹“ testfolder”获取文件名,并将其转储到csv文件中。
Code: 码:
import os, csv
f = open("/home/niteninja/Documents/sampledata.csv", 'r+')
w=csv.writer(f)
for path, dirs, files in os.walk("/home/niteninja/testfolder"):
for filename in files:
w.writerow([filename])
f.truncate()
This is an example of what the data in the csv file looks like after running the code above. 这是运行上面的代码后csv文件中数据的外观示例。
sampledata.csv: sampledata.csv:
A B
ndjsmdhfr_145874
jdmsjfht_273647
hfgryuyw_756475
jgmfhdhr_736453
jdmsdhfyt_548745
What I want to do is implement this formula : "LEFT(A1,FIND("_",A1) - 1)"
in column B. 我要做的是在B列中实现以下公式:
"LEFT(A1,FIND("_",A1) - 1)"
。
The purpose of this is to eliminate the underscores and any characters that come after it. 这样做的目的是消除下划线和其后的所有字符。 I want to be able to apply this formula to the cells in column A and output the new values to column B. I am unable to figure out the proper syntax to approach this problem.
我希望能够将此公式应用于A列中的单元格,并将新值输出到B列。我无法找出解决此问题的正确语法。
First define a function for a single string: 首先为单个字符串定义一个函数:
def splitter(x):
return x.split('_')[0]
print(splitter('ndjsmdhfr_145874'))
# ndjsmdhfr
Then write to your CSV file. 然后写入您的CSV文件。 Remember to use
newline=''
as an argument to open
. 请记住使用
newline=''
作为open
的参数。 In addition, it's recommended you use the with open(...)
construct for reading / writing files. 另外,建议您使用
with open(...)
构造读取/写入文件。 Here's some pseudo-code: 这是一些伪代码:
with open('out_file.csv', 'w', newline='') as fout:
w = csv.writer(fout)
for path, dirs, files in os.walk("/home/niteninja/testfolder"):
for filename in files:
w.writerow([filename, splitter(filename)])
These three lines of code will select the first cell in column B and apply the formula, then copy it down the column 这三行代码将选择B列中的第一个单元格并应用公式,然后将其复制到该列中
Range("B1").Select
ActiveCell.FormulaR1C1 = "=LEFT(RC[-1],FIND(""_"",RC[-1]) - 1)"
Selection.AutoFill Range(ActiveCell, ActiveCell.Offset(0, -1).End(xlDown).Offset(0, 1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.