将列表添加到数据框中的单元格是基于2种条件,以删除每个列表中的元素

问题描述 投票:0回答:2

我在数据帧中有两列,第一列在每个单元格中都有一个数字列表,第二列在每个单元格中都有一个字母列表。考虑以下条件,我想再创建两列:

当“ A”列中的值小于1时,该值将保留在列表中,而其他值将被删除,在这种情况下,与“ A”列中的数字具有相同索引的字母

Table

输出:

enter image description here

我无法在datframe中执行此操作,因此我尝试创建一个列表列表,然后将它们添加为列,但是如果我仅使用一个列表但该列不起作用,则可以正常工作。

我想要一些建议。


big_a = []
big_b = []

new_list_a = []
new_list_b = []
for a, b in zip(x['COLUMN_A'], x['COLUMN_B']):
    if a < 1:
        new_list_a = []
        new_list_b = []
        new_list_a.append(a)
        new_list_b.append(b)   
        big_a.append(new_list_a)
        big_b.append(new_list_b)    

这给我以下错误:

TypeError: '<' not supported between instances of 'list' and 'int'
python pandas dataframe conditional-statements
2个回答
1
投票

这可能对您有用:

        import numpy as np
        import pandas as pd


        def fun(row):
          np_A=np.array(row.COLUMN_A)
          np_B=np.array(row.COLUMN_B)

        return np_A[np_A<1] , np_B[np_A<1] 


    df[["NEW_A","NEW_B"]]=df.apply(lambda row: pd.Series(fun(row)), axis=1)

0
投票
import numpy as np
import pandas as pd

# Create the dataframe
df = pd.DataFrame({
    'A': [[0.99, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 0.25, 0.87]],
    'B': [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
})

# Convert the lists to numpy ndarray
df = df.applymap(np.asarray)

# Explode the dataframe
df = df.reset_index().apply(pd.Series.explode).set_index(['index', 'B'])

# Filter for rows whose value for column 'A' is less than 1
df = df[df < 1].dropna().reset_index().groupby('index').agg(list)

最终的DataFrame看起来像:

      B     A
index       
0    [a]    [0.99]
2    [b, c] [0.25, 0.87]

注意:

找到有关熊猫爆炸here的更多详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.