首页 > 解决方案 > 需要有关 excel python 数据抓取任务的帮助

问题描述

我最近刚开始学习 python(已经学习了 6 周),我不知道如何攻击这个任务。对于这项任务,我们从 Twitter 获得了一个 excel 数据集,并应该“抓取数据”。

我应该在你拥有的数据集中找到唯一的用户名和他们在 Twitter 上发推文的次数(不包括转发和回复)。并找出推文数量最多的前 10 位用户(不包括转发和回复)。

我一直在使用 pandas,但我找不到正确的代码字符串来完成我所需要的。

我能够使用此代码过滤所有仅发送“推文”的用户。这似乎是我唯一的突破。

df.loc[df['Relationship'] == "Tweet"]

在数据集中有一列包含用户名“Users1”(即他们的推特句柄)和一个名为“Relationship”的列(即提及、回复、推文)。这是我一直在使用的两个专栏。

不幸的是,我在我的头上,需要任何可能的帮助。

谢谢

编辑:

print(df.User1.value_counts(['Relationship'] == "Tweet"))

能够使用此代码取得一些进展^

这确实是我发现的唯一半有用的代码字符串。我已经吐了一个多小时了。

我附上了部分数据的图片。部分数据

标签: pythonpandas

解决方案


The first thing you want to do is add a 'tweetcount' column for each User1, I think. If each linebreak represents a tweet, that just means counting the endlines ('\n') in each tweet string.

For finding unique elements in a column of data in a pandas dataframe, this should work, if you have imported numpy as np:

#generate a numpy array from the dataframe:
names = df[['username']].to_numpy()
#generate a simple list from the numpy array (flatten the array):
temp = [x for items in names for x in items]
#extract the unique elements from the simple list using the count method:
uniques = [x for x in temp if temp.count(x) == 1]

Now you have a list of unique names, to extract the index values from your pandas df:

indices = [x for x in range(len(df)) if df.loc[x, 'username'] in uniques]

To get the full row of data for each unique username:

for x in indices:
    print(df.loc[x, 'username'], df.loc[x, 'tweetcount'])

Sorting by a given column in a pandas dataframe is much simpler (and their might be a simpler solution for this as well). Just use:

df.sort_values(by='tweetcount')

推荐阅读