【问题标题】:How to create a new Pandas dataframe column from other columns in the dataframe如何从数据框中的其他列创建新的 Pandas 数据框列
【发布时间】:2017-06-29 00:44:52
【问题描述】:

我有一个活动列表,popular_activities,如下:

['google.co.uk', 'whatsapp', 'sharelatex.com', 'Financial Times', 'other',                 
'en.wikipedia.org', 'Instagram for Android', 'YouTube for Android', 
'arxiv-sanity.com', 'quora.com', 'microsoft word', 'Inbox by Gmail', 
'Google Chrome for Android', 'youtube.com', 'mendeley desktop', 
'web.whatsapp.com', 'Preview', 'texshop', 'Google Now', 'mobile - 
com.compassnews.app', 'netflix.com', 'WhatsApp Messenger Android', 'Facebook 
for Android', 'arxiv.org']

我还有一个DataFrame如下:

                       Activity                           Time Spent (seconds)
Date                                                                       
2017-03-25T00:05:00    [netflix.com, other, Google Now]   [30, 6, 2]
2017-03-25T00:10:00    [netflix.com]                      [300]
2017-03-25T00:15:00    [netflix.com]                      [102]   
2017-03-25T00:30:00    [netflix.com]                      [232]   
2017-03-25T00:35:00    [netflix.com]                      [279] 

我想在这个 DataFrame 'Activity_vector' 中创建一个新列,这样该列中的每个元素都是一个长度等于 popular_activities 的向量,其中活动的相应索引(如在 popular_activities 数组中)包含在该活动上花费的时间。

因此,例如,对于日期为 2017-03-25T00:05:00 的第二个元素,新列“Activity_vector”中的对应元素将是

[0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 30, 0, 0, 0]

这样,在 popular_activities 中对应的“花费时间(秒)”值为 30 且索引为 21 的“活动”netflix.com 将拥有一个索引为 21 且填充值为 30 的数组,' Activity' other 的对应索引 (4) 将填充值 6,对于 Google Now 也是如此。

下面是我所拥有的 sn-p,其中 self.clean_df 是讨论的 DataFrame:

class Clean_DF(object):
....
    def clean_data(self, time_percentage):
    ....
        self.clean_df['Activity_vector'] = self.clean_df.apply(lambda x: self.activity_to_vector(x),axis=1)

    def activity_to_vector(self, row):
        vect = np.zeros(len(self.popular_apps))
        for x,y in zip(row['Activity'], row['Time Spent (seconds)']):
            vect[self.popular_apps_dict[x]] += vect[self.popular_apps_dict[x]] + y
        return vect

但是,当我运行它时,我收到以下错误

ValueError: Shape of passed values is (3862, 24), indices imply (3862, 2)

我该如何解决这个错误/编写一个函数来解决我的问题?

【问题讨论】:

    标签: python pandas dataframe series


    【解决方案1】:
    num = len(popular_activities)
    
    def make_array(s):
        z = [0] * num
        time = s['Time Spent (seconds)']
        for i, val in enumerate(s['Activity']):
            idx = popular_activity.index(val)
            z[idx] = time[i]
        return z
    
    df.apply(make_array, axis=1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-05
      • 2020-04-12
      相关资源
      最近更新 更多