【问题标题】:Appending new elements to a column in pandas dataframe将新元素附加到熊猫数据框中的列
【发布时间】:2019-04-01 16:54:51
【问题描述】:

我有一个这样的熊猫数据框:

df1:                              
    id  name   gender
    1   Alice  Male 
    2   Jenny  Female
    3   Bob    Male

现在我想添加一个新的列运动,它将包含列表形式的值。让我想将足球添加到性别为男性的行中,所以 df1 看起来像:

df1:                              
        id  name   gender  sport
        1   Alice  Male    [Football]
        2   Jenny  Female   NA
        3   Bob    Male    [Football]

现在,如果我想将 Badminton 添加到性别为女性的行,将网球添加到性别为男性的行,最终输出为:

df1:                              
            id  name   gender  sport
            1   Alice  Male    [Football,Tennis]
            2   Jenny  Female  [Badminton]
            3   Bob    Male    [Football,Tennis]

如何在python中编写一个通用函数来完成根据其他列值将新值附加到列中的任务?

【问题讨论】:

  • 没有这样的通用函数。 或者,如果你选择炮制一个,它会与 Pandas 使用容器作为序列值背道而驰。可能,自定义类或dict + list 是更合适的数据结构选择。

标签: python-3.x pandas


【解决方案1】:

以下内容应该适合您。用空列表初始化列并继续

df['sport'] = np.empty((len(df), 0)).tolist()

def append_sport(df, filter_df, sport):
    df.loc[filter_df, 'sport'] = df.loc[filter_df, 'sport'].apply(lambda x: x.append(sport) or x)
    return df

filter_df = (df.gender == 'Male')
df = append_sport(df, filter_df, 'Football')
df = append_sport(df, filter_df, 'Cricket')

输出

    id  name    gender  sport
0   1   Alice   Male    [Football, Cricket]
1   2   Jenny   Female  []
2   3   Bob     Male    [Football, Cricket]

【讨论】:

    猜你喜欢
    • 2014-01-03
    • 1970-01-01
    • 2019-01-14
    • 2020-05-21
    • 2020-11-17
    • 2018-02-08
    • 2017-06-13
    • 2020-09-26
    • 2013-11-18
    相关资源
    最近更新 更多