在Pandas中使用For循环的数据帧

时间:2018-05-05 03:54:29

标签: python pandas loops for-loop dataframe

我需要像这样运行代码行。

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

创建和尝试的功能就像这样,

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

但是,它会给出错误,

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

请帮助

2 个答案:

答案 0 :(得分:1)

尝试使用locals

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

答案 1 :(得分:0)

我终于搞定了,代码如下,

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')

如果只能简化此代码。