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

Categories

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

python - I have a problem with a for. How can I loop through the for and add the data to a list?

I have this dataframe (compressed):

year    month      name

2000    January    car
2000    January    bike
2000    February   train
2000    May        car
2001    January    bike
2001    February   car
2001    February   bike
2001    July       car
2002    January    car
2002    February   train
2002    March      bike
2002    July       car

I need to add the data for 2001 and February to a list, for this I have made the following code.

name2001 = []
for year in df['year']:
    if year == 2001:
        for month in df['month']:
            if month == 'February':
                for name in df['name']:
                    name2001.append(name)

I was debugging and I got this error:

'Too large to show contents. Max items to show: 300'

I changed it to 10000 and I get this error:

'Too large to show contents. Max items to show: 10000'

But I know that approximately 5000 data must be added.

What is wrong with the for-loop?

question from:https://stackoverflow.com/questions/65617553/i-have-a-problem-with-a-for-how-can-i-loop-through-the-for-and-add-the-data-to

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

1 Reply

0 votes
by (71.8m points)

You can do, for example:

df[df.year.eq(2001) & df.month.str.contains('February')].name

which will give you the contents of column name, which have 2001 in their year column and February in their month column.

If want a list:

df[df.year.eq(2001) & df.month.str.contains('February')].name.to_list()

giving you:

['car', 'bike']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...