Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将单索引数据帧转换为多索引_Python_Pandas_Twitter_Multi Index - Fatal编程技术网

Python 将单索引数据帧转换为多索引

Python 将单索引数据帧转换为多索引,python,pandas,twitter,multi-index,Python,Pandas,Twitter,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')

我有一个具有以下结构的数据框:

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')
我想把这个数据帧转换成一个多索引帧,基本上是通过破坏包含tweets的单元格。一个索引是uid,另一个是tweet中的id

我该怎么做


因此,从df中,您有包含推文df的推文列,因此我创建了一个
tweets\u df
数据帧,并将推文中的所有df连接到
tweets\u df
,添加uid列以了解推文属于哪个uid,然后将uid信息合并到
tweets\u 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_tweets={'created_at':a,'id':b,'retweet_count':c,'text:d1
的事情吗?然后对于你的主
df
do
df={…'tweets':df2'…}
?我误解了你的要求,忽略这个。你能发布样本数据吗?@AndrewL,我添加了样本数据。