将单索引 pandas 数据框转换为多索引
convert single index pandas data frame to multi-index
我有一个具有以下结构的数据框:
df.columns
Index(['first_post_date', 'followers_count', 'friends_count',
'last_post_date','min_retweet', 'retweet_count', 'screen_name',
'tweet_count', 'tweet_with_max_retweet', 'tweets', 'uid'],
dtype='object')
在 tweets 系列中,每个单元格都是包含用户所有 tweets 的另一个数据框。
df.tweets[0].columns
Index(['created_at', 'id', 'retweet_count', 'text'], dtype='object')
我想将此数据框转换为多索引框,主要是通过拆分包含推文的单元格。一个索引将是 uid,另一个将是 tweet.[=14= 中的 id ]
我该怎么做?
所以从 df 开始,你有包含推文 df 的推文列,所以我创建了一个 tweets_df
数据框并将推文中的所有 df 连接到 tweets_df
,添加 uid 列以了解哪个 uid该推文属于,然后将 uid 的信息合并到 tweets_df
以在需要时进行进一步处理。如果您需要进一步修改,请发表评论。很难获取样本数据并转换为 json。所以我在猜测中做了这个,希望它仍然能给你一些想法。
import pandas as pd
df = .... #your df
tweets_df = pd.DataFrame() #create blank df to contain tweets
# explode tweets to df
## loop each uid
for uid in df['uid']:
temp = df.loc[df['uid']==uid, :] # select df by uid
temp = temp['tweets'].iloc[0] # select tweets column -> df
temp['uid'] = uid # add uid column to know tweets belong to which uid
tweets_df = pd.concat([results, temp], ignore_index=True) # concat to container df
# get a uid info df from starting df
uid_info_column = df.columns
uid_info_column.remove('tweets')
uid_info_df = df.loc[:, uid_info_column]
# merge info on uid with tweets_df
final = pd.merge(left=tweets_df, right=uid_info_df, on='uid', how='outer')
我有一个具有以下结构的数据框:
df.columns
Index(['first_post_date', 'followers_count', 'friends_count',
'last_post_date','min_retweet', 'retweet_count', 'screen_name',
'tweet_count', 'tweet_with_max_retweet', 'tweets', 'uid'],
dtype='object')
在 tweets 系列中,每个单元格都是包含用户所有 tweets 的另一个数据框。
df.tweets[0].columns
Index(['created_at', 'id', 'retweet_count', 'text'], dtype='object')
我想将此数据框转换为多索引框,主要是通过拆分包含推文的单元格。一个索引将是 uid,另一个将是 tweet.[=14= 中的 id ]
我该怎么做?
所以从 df 开始,你有包含推文 df 的推文列,所以我创建了一个 tweets_df
数据框并将推文中的所有 df 连接到 tweets_df
,添加 uid 列以了解哪个 uid该推文属于,然后将 uid 的信息合并到 tweets_df
以在需要时进行进一步处理。如果您需要进一步修改,请发表评论。很难获取样本数据并转换为 json。所以我在猜测中做了这个,希望它仍然能给你一些想法。
import pandas as pd
df = .... #your df
tweets_df = pd.DataFrame() #create blank df to contain tweets
# explode tweets to df
## loop each uid
for uid in df['uid']:
temp = df.loc[df['uid']==uid, :] # select df by uid
temp = temp['tweets'].iloc[0] # select tweets column -> df
temp['uid'] = uid # add uid column to know tweets belong to which uid
tweets_df = pd.concat([results, temp], ignore_index=True) # concat to container df
# get a uid info df from starting df
uid_info_column = df.columns
uid_info_column.remove('tweets')
uid_info_df = df.loc[:, uid_info_column]
# merge info on uid with tweets_df
final = pd.merge(left=tweets_df, right=uid_info_df, on='uid', how='outer')