1

I need to run the code lines something like this.

tweet24042018 = tweets.loc[tweets['date2'] == '24042018'].copy()
tweet23042018 = tweets.loc[tweets['date2'] == '23042018'].copy()
tweet22042018 = tweets.loc[tweets['date2'] == '22042018'].copy()

The function created and tried is like this,

for key in collect:
    ['tweet'+f'{key}'] = tweets.loc[tweets['date2'] == f'{key}'].copy()

But, it gives error like,

File "<ipython-input-18-3c946d8cc61a>", line 2
['tweet'+f'{key}'] = tweets.loc[tweets['date2'] == f'{key}'].copy()
^
 SyntaxError: can't assign to operator 

help please

1
  • collect is collect = ['22042018', '23042018', '24042018'] Commented May 5, 2018 at 3:55

2 Answers 2

1

Try using locals

variables = locals()
for key in collect:
    variables["tweet{0}".format(key)]= tweets.loc[tweets['date2'] == key]
    print(variables["tweet{0}".format(key)].head())
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that works but I need to verify its output so how to use this code piece tweet22042018.head() in the loop so that all the dataframes can be displayed.
Please I need to iterate this code tweet24042018.to_csv("tweet24042018.csv", index = False, header = True, encoding = 'utf-8') for the values in y = ['tweet22042018', 'tweet23042018', 'tweet24042018']
do you need the variables, or do you just need to save all of these as csvs?
I have tried this for key in y: k = "{0}".format(key) z = "{0}".format(key) + ".csv" k.to_csv(z, sep=',') but it fails.
0

I finally got it working, the code is as follows,

variables = locals()
 y = []
 for key in collect:
 variables["tweet{0}".format(key)]= tweets.loc[tweets['date2'] == 
 key].copy()

variables["tweet{0}".format(key)].to_csv("tweet{0}".format(key)+'.csv', 
 index = False, header = True, encoding = 'utf-8')

If only this code can be simplified.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.