寻找一种有效地对某列数据进行计算的方法

2024-09-25 00:23:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试查看熊猫数据帧的特定列,并尝试执行以下操作:

col0 col1   col2
int0 float0 str0
int1 float1 str0
int2 float2 str1

我试图逐行遍历该列上的数据帧,但这似乎效率不高。。lambda是一个选项,但我不确定是否有类似于DataFrame列的“列表理解”(据我所知,这是Pandas系列)。你知道吗

比如说,如果DataFrame被定义为df,那么我想做一些事情,比如:

for row in df:
    if df['col2'] == str0:
        # do some calculation for all str0 types
    elif df['col2'] == str1:
        # do another calculation for all str1 types
    else:
        # do another calculation for all other types (which are actually str2 types implied by the if-elif-else statement)

为了得到一个单独的NumPy矩阵,它将创建一个与DataFrame的相应行相对应的NumPy行。通过检查“col2”的条件,将根据其值执行单独的计算,并生成相应numy数组的行。你知道吗

请让我知道是否有一个有效的方法(无论是在规范,python编码以及时间和内存效率方面)!我们将不胜感激。你知道吗


Tags: 数据dataframedfforifanotheralldo
3条回答

您可以首先分离出与col2列的每个值对应的行。你知道吗

>>> df = pd.DataFrame(dict(col0=[0,1,2], col1=[3.0, 4.0, 5.0], col2=['str0', 'str0', 'str1']))
>>> col2_elm_to_df = {col2_elm: group_df for col2_elm, group_df in df.groupby('col2')}
>>> col2_elm_to_df
{
    'str0':          col0  col1  col2
               0     0     3.0   str0
               1     1     4.0   str0, 

    'str1':          col0  col1  col2
               2     2     5.0   str1
}

这更像是一个np.select问题

condition = [df['col2'] == str0, df['col2'] == str1...]
Target = [function1 , function2...]

df['NewCol'] = np.select(condition , Target , default = np.nan )

从维护角度来看,最简单的事情是创建一个函数,例如:

def fn(x):
    if x < 5:
        return x * 2
    else:
        return x * 3

然后将其应用于您的专栏:

df["col2"].apply(fn)

相关问题 更多 >