Python 我可以将lambda函数应用于特定行上的df列吗?

Python 我可以将lambda函数应用于特定行上的df列吗?,python,function,lambda,Python,Function,Lambda,python新手,请容忍我 我有一个函数,可以将随机值应用于df中的不同列(取决于列名;每列都有特定的随机值范围)。对于一个特定的函数,我只想将其应用于我的列的一半。我试图用偶数行来处理这个问题,但似乎不起作用。当我打印出前几行时,我可以看出列没有更新。非常感谢您的帮助 以下是我的尝试: for col in df.columns: if 'shirt' in col: df[col] = df[col].apply(lambda x: np.ra

python新手,请容忍我

我有一个函数,可以将随机值应用于df中的不同列(取决于列名;每列都有特定的随机值范围)。对于一个特定的函数,我只想将其应用于我的列的一半。我试图用偶数行来处理这个问题,但似乎不起作用。当我打印出前几行时,我可以看出列没有更新。非常感谢您的帮助

以下是我的尝试:

    for col in df.columns:
        if 'shirt' in col:
            df[col] = df[col].apply(lambda x: np.random.randint(0,5))
        elif 'pants' in col:
            df[col] = df[col].apply(lambda x: np.random.randint(0,10))
        elif 'sweater' in col:
            df[col] = df[col].apply(lambda x: np.random.randint(0,50) if df.index.all() % 2 == 0 else np.NaN)
        else:
            pass
(不得不添加
.all()
bc我得到了一个
值错误:一个包含多个元素的数组的真值是不明确的
错误。)

使用索引将其应用于我的数据帧的一半是我所能想到的,但是如果我想将lambda函数仅应用于我的列的60%或80%,而将其余部分保留为null,这是行不通的

这是我从上述代码中得到的结果:

    shirt_count  pant_count  sweater_count  
0            14            3            5 
1            18            3            7 
2             1            3            5 
3             7            1            9 
4             2            3            2 

我已经盯着屏幕看了好几个小时了,希望能得到任何帮助

您可以对“毛衣”列的偶数行和奇数行应用单独的函数:

import pandas as pd
import numpy as np

df = pd.DataFrame({'shirt': [0,0,0,0,0], 'pants': [0,0,0,0,0], 'sweater': [0,0,0,0,0]})

for col in df.columns:
    if 'shirt' in col:
        df[col] = df[col].apply(lambda x: np.random.randint(0,5))
    elif 'pants' in col:
        df[col] = df[col].apply(lambda x: np.random.randint(0,10))
    elif 'sweater' in col:
        # random integers for even rows
        df[col][::2] = df[col][::2].apply(lambda x: np.random.randint(0,50))

        # na.NaN for odd rows
        df[col][1::2] = df[col][1::2].apply(lambda x: np.NaN)
    else:
        pass
输出:

>>> df
   shirt  pants  sweater
0      4      9      0.0
1      0      1      NaN
2      2      7     28.0
3      2      7      NaN
4      0      8     30.0

您可以对“毛衣”列的偶数行和奇数行应用单独的函数:

import pandas as pd
import numpy as np

df = pd.DataFrame({'shirt': [0,0,0,0,0], 'pants': [0,0,0,0,0], 'sweater': [0,0,0,0,0]})

for col in df.columns:
    if 'shirt' in col:
        df[col] = df[col].apply(lambda x: np.random.randint(0,5))
    elif 'pants' in col:
        df[col] = df[col].apply(lambda x: np.random.randint(0,10))
    elif 'sweater' in col:
        # random integers for even rows
        df[col][::2] = df[col][::2].apply(lambda x: np.random.randint(0,50))

        # na.NaN for odd rows
        df[col][1::2] = df[col][1::2].apply(lambda x: np.NaN)
    else:
        pass
输出:

>>> df
   shirt  pants  sweater
0      4      9      0.0
1      0      1      NaN
2      2      7     28.0
3      2      7      NaN
4      0      8     30.0