简体   繁体   中英

How to write rows to a .csv file using .iloc in pandas python

I am searching a .csv file for some numbers using a regular expression. Then when the numbers match, the index of those rows is written to a .csv using .iloc but getting an error.

for each in temp:

      if doLuhn(str(each)) is True:
          #print ("In the loop")
          creditcards.append(each)
          Validcardsfound = Validcardsfound + 1
          regex_match_index_list.append(i)

then

for each in regex_match_index_list:
df.iloc[each].to_csv('test.csv')

Note : I have create an empty dataframe df.

But I am getting the following error

IndexError: single positional indexer is out-of-bounds

Try putting in the number of columns after .iloc instead of "each". Lets say you have 18 columns try the following: df.iloc[:,17].to_csv('test.csv')

If you want to write the list that you created based on some requirement (regex_match_index_list) to a file test.csv: maybe you can try converting it to a data frame of one column and write it.

import pandas as pd
pd.DataFrame(regex_match_index_list, columns=['column_name_you_want']).to_csv('test.csv')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM