[英]Writing data to specific column in python using pandas
I have an Excel Sheet where for some of the columns uniqueidentifier
is set to "yes" and for rest of them it is blank. 我有一个Excel工作表 ,其中某些列的uniqueidentifier
设置为“是”,其余部分为空白。
Using the Pandas library , I get the data that have no value in uniqueidentifier
using the following command: 使用Pandas库 ,我使用以下命令获取uniqueidentifier
没有值的数据:
df=pandas.read_excel("sample.xlsx")
df=df[df.uniqueidentifier != "yes"]
I then want to write "yes" to the uniqueidenfier
column every time I loop through the index in the excel file. 然后,我每次循环浏览excel文件中的索引时都想在uniqueidenfier
列中写“ yes”。
list=[]
for i in df.index
list.append(df['Subject'][i])
# do some function here
var="some value"
Every time I get the proper values in list
and in var
for the respective index. 每次我在list
和var
中获得相应索引的正确值时。 I want my function to write something to the uniqueidentifier
column for that i
value in the loop (for example, if in row 4, then when uniqueidentifier
is not set, the list should take the value from the subject and append and write "yes" to uniqueidentifier
column) 我希望我的函数在循环中为i
值向uniqueidentifier
列中写入一些内容(例如,如果在第4行中,则未设置uniqueidentifier
时,列表应从主题中获取值并追加并写入“是”到uniqueidentifier
列)
In addition to the above, I want to write the var
value to an adjacent column in the excel file. 除了上述内容,我想将var
值写入excel文件中的相邻列。
Could someone help me as I am new to python and stuck here? 当我刚接触python并被困在这里时,有人可以帮我吗?
to set the unique identifier to be yes you can add to your loop the foloowing line: 要将唯一标识符设置为是,可以将以下行添加到循环中:
if [#some conditions are met]:
df.loc[i,'uniqueidentifier']='YES'
df.iloc[i].new_column=var
#new_column is the name of the column where you write your var value. you can name it however you want.
then you need to export it back to excel. 那么您需要将其导出回excel。 you can use: 您可以使用:
writer = pd.ExcelWriter('file.xlsx')
df.to_excel(writer,'Sheet1')
writer.save()
but keep in mind this will overwrite your old excel 但请记住,这将覆盖您的旧版Excel
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.