gpt4 book ai didi

python - 如何在 Pandas 中实现 if/elif/else 语句 (Python)

转载 作者:太空宇宙 更新时间:2023-11-03 15:55:44 25 4
gpt4 key购买 nike

我一直在做一个项目,需要填写“向量”月份(制作直方图:每月推文数量的概述)。为了填写矢量月,我编写了以下代码:

numTweets = list(tweets_cleaned_panda.iloc[:,1])

months = [0, 0, 0, 0, 0, 0, 0]
for i in range(0,len(numTweets)+1):

if tweets_cleaned_panda['created_at'].str.contains("Mar") or tweets_cleaned_panda['created_at'].str.contains("Apr"):
months[0] = months[0] + 1
elif tweets_cleaned_panda['created_at'].str.contains("May"):
months[1] += 1
elif tweets_cleaned_panda['created_at'].str.contains("Jun"):
months[2] += 1
elif tweets_cleaned_panda['created_at'].str.contains("Jul"):
months[3] += 1
elif tweets_cleaned_panda['created_at'].str.contains("Aug"):
months[4] += 1
elif tweets_cleaned_panda['created_at'].str.contains("Sept"):
months[5] += 1
else:
months[6] += 1
print months

我尝试将 .any() 附加到 contains() 语句的末尾,但它只填充月份[0]。

此外,我编写了以下代码:

for i in range(0,len(numTweets)+1):
np.where(tweets_cleaned_panda['created_at'].str.contains("Mar"),
months[0] = months[0] + 1,
np.where(tweets_cleaned_panda['created_at'].str.contains("Apr"),
months[0] = months[0] + 1,
np.where(tweets_cleaned_panda['created_at'].str.contains("May"),
months[1] = months[1] + 1,
np.where(tweets_cleaned_panda['created_at'].str.contains("Jun"),
months[2] = months[2] + 1,
np.where(tweets_cleaned_panda['created_at'].str.contains("Jul"),
months[3] = months[3] + 1,
np.where(tweets_cleaned_panda['created_at'].str.contains("Aug"),
months[4] = months[4] + 1,
np.where(tweets_cleaned_panda['created_at'].str.contains("Sept"),
months[5] = months[5] + 1,
np.where(tweets_cleaned_panda['created_at'].str.contains("Oct"),
months[6] =months[]+ 1))))))))

但这给出了以下错误:

SyntaxError: keyword can't be an expression File "", line 10 months[0] = months[0] + 1, SyntaxError: keyword can't be an expression

有谁可以帮忙吗?

最佳答案

pandas 非常适合处理日期时间数据。使用 pd.to_datetime 函数您可以转换 UTC 格式的时间:

pd.to_datetime("Wed Aug 27 13:08:45 +0000 2008")
Out Timestamp('2008-08-27 13:08:45')

如果您首先使用以下方式转换该列:

df['created_at'] = pd.to_datetime(df['created_at'])

然后您可以对月份列使用 .dt 访问器:

df['month'] = df['created_at'].dt.month

要从中获取频率分布,您所需要做的就是调用 value_counts:

df['month'].value_counts()

注意:您需要将 df 替换为 DataFrame 的名称 (tweets_cleaned_pa​​nda)。

关于python - 如何在 Pandas 中实现 if/elif/else 语句 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40823399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com