Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
6.7k views
in Technique[技术] by (71.8m points)

python - Pandas.DataFrame.loc(. . .) - TypeError: list indices must be integers or slices, not str

for t in teams:
eventsByTeam[str(t)] = df.loc[(df['teamId'] == t) & (df['positions'][0]['x'] == 50)]

The above code will not run, citing a TypeError: list indices must be integers or slices, not str in reference to the second condition passed to df.loc()

df is of course a pandas DataFrame. 'positions' is a column therein, and each row of that column contains [{'y': 123, 'x': 456}, {'y': 789, 'x': 42069}]. So a list of dictionaries, and I want the 'x' value in the first element of the list.

If I take that second condition out, this snippet runs and I get a dict called eventsByTeam with smaller DataFrames (as expected). If I run the following:

 for item in eventsByTeam.items():

     for i, event in item[1].iterrows():
    
         if event['positions'][0]['x'] == 50:

             # do a thing

The programme does the thing without complaint. So why does it complain in the first instance?

Sorry if I've left anything out; happy to provide more information. TIA.

question from:https://stackoverflow.com/questions/65946324/pandas-dataframe-loc-typeerror-list-indices-must-be-integers-or-slices

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...