Pandas - Dataframe 中列中重复值或列表值的列添加

爱尔兰共和军

假设一个数据框看起来像这样

  one  two 
a  1.0  1.0 
b  2.0  2.0 
c  3.0  3.0 
d  NaN  4.0 

添加新的三列是这样的

df["three"] = df["one"] * df["two"]

结果

   one  two     three 
 a  1.0  1.0    1.0 
 b  2.0  2.0    4.0 
 c  3.0  3.0    9.0   
 d  NaN  4.0    NaN  

包含重复列表或列表的列值怎么样,我需要创建一个新列并添加具有最高值的数字

例子

    one  two 
 a  1.0  [12,1]
         [12,1]
 b  2.0  2.0    
 c  3.0  3.0    
 d  NaN  4.0    

所以我想要这样

    one  two        flag
 a  1.0  [12,1]      12
         [12,1]
 b  2.0  [200,400]   400
 c  3.0  3.0         3.0
 d  NaN  4.0         4.0

谢谢

耶兹瑞尔

如果有列表或嵌套列表或浮点数,您可以使用以下方法展平列表max

df = pd.DataFrame({"two":  [[[12,1],[12,1]] ,[200,400] ,3.0,4.0 ]})
    
from typing import Iterable 
              
#https://stackoverflow.com/a/40857703/2901002
def flatten(items):
    """Yield items from any nested iterable; see Reference."""
    for x in items:
        if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
            for sub_x in flatten(x):
                yield sub_x
        else:
            yield x
            
df['new'] = [max(flatten(x)) if isinstance(x, list) else x for x in df['two']]
print (df)
                  two    new
0  [[12, 1], [12, 1]]   12.0
1          [200, 400]  400.0
2                 3.0    3.0
3                 4.0    4.0

编辑:对于所有列的新 DataFrame 中的最大值,请使用聚合函数max

df = df_orig.pivot_table(index=['keyword_name','volume'], 
                    columns='asin', 
                    values='rank', 
                    aggfunc=list)

df1 = df_orig.pivot_table(index=['keyword_name','volume'], 
                     columns='asin', 
                     values='rank', 
                     aggfunc='max')

out = pd.concat([df, df1.add_suffix('_max')], axis=1)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Pandas DataFrame中列的值列表

将列添加到包含其他列值列表的pandas DataFrame中

Pandas Dataframe检查列值是否在列列表中

如何根据Pandas DataFrame中的条件添加每组重复值的新列?

根据列值在pandas DataFrame中重复行

删除Pandas中的DataFrame行,其中列值在列表中

选择列表中的Pandas DataFrame列值的所有行

按列列表中的值过滤Pandas DataFrame

如何转换pandas Dataframe中的列值?

替换pandas DataFrame中的列值

Pandas DataFrame填充列中的缺失值

Pandas DataFrame从列中检索值

根据值在Pandas中删除DataFrame列

在Pandas中的DataFrame中为每个索引值添加列表

根据另一个列表从pandas dataframe列中的列表中删除值

将Pandas DataFrame中的列值与“ NaN”值连接

Python Pandas DataFrame检查一列的值是否在另一列表中

Pandas - 基于特定列的值在 DataFrame 中创建单独的列

如何从列类型列表中从Pandas DataFrame中删除空值

通过从列表中获取值,基于列值动态删除Pandas中的DataFrame行

如果列值的组合等于列表中的元组,则删除Pandas中的dataFrame行

當列值與列表中的元組匹配時,刪除 Pandas Dataframe 中的行

根据pandas DataFrame中的条件替换列中的值

在Pandas DataFrame中添加新列时结果不一致。是系列还是值?

给定输入值列表,如何计算 Python 中的 Pandas DataFrame 列的计数?

给定该列中已排序的值列表,如何在该列上对 Pandas DataFrame 进行排序?

Pandas Dataframe - 对列的每一行中的值列表进行排序

检查pandas dataframe列中的值是否为整数,如果不是,则将其写入列表

如何将带有值列表的列转换为Pandas DataFrame中的行