How to iterate over a CSV file with Pywikibot

101 views Asked by At

I wanted to try uploading a series of items to test.wikidata, creating the item and then adding a statement of inception P571. The csv file sometimes has a date value, sometimes not. When no date value is given, I want to write out a placeholder 'some value'.

Imagine a dataframe like this:

df = {'Object': [1, 2,3], 'Date': [250,,300]}

However, I am not sure using Pywikibot how to iterate over a csv file with pywikibot to create an item for each row and add a statement. Here is the code I wrote:

import pywikibot 
import pandas as pd
site = pywikibot.Site("test", "wikidata")
repo = site.data_repository()
df = pd.read_csv('experiment.csv')
item = pywikibot.ItemPage(repo)
for item in df:
    date = df['date']
    prop_date = pywikibot.Claim(repo, u'P571')
    if date=='':
        prop_date.setSnakType('somevalue')
    else:
        target = pywikibot.WbTime(year=date)
        prop_date.setTarget(target)
    item.addClaim(prop_date)

When I run this through PAWS, I get the message: KeyError: 'date'

But I think the real issue here is that I am not sure how to get Pywikibot to iterate over each row of the dataframe and create a new claim for each new date value. I would value any feedback or suggestions for good examples and documentation. Many thanks!

1

There are 1 answers

0
kylemaxim On

Looking back on this, the solution was to use .iterrows() or .itertuples() or .loc[] to access the values in the row.

So

for item in df.itertuples():       
prop_date = pywikibot.Claim(repo, u'P571')
   if item.date=='':
        prop_date.setSnakType('somevalue')
    else:
        target = pywikibot.WbTime(year=date)
        prop_date.setTarget(target)
    item.addClaim(prop_date)