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

2024-09-30 05:20:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要像这样运行代码行。你知道吗

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 

请帮帮我


Tags: key函数代码infor错误loctweets
2条回答

尝试使用locals

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

我终于成功了,代码如下

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

如果这段代码可以简化就好了。你知道吗

相关问题 更多 >

    热门问题