Pandas dataframe:如何将索引后的值设置为0

2024-04-25 05:23:13 发布

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

我有一个Pandas数据帧,每行包含一个名称,列中有许多数字。在为每一行指定索引(在每一行中唯一计算)之后,我希望将该行中的所有剩余值设置为0。在

因此,我尝试了一些方法,并获得了以下工作代码:

for i in range(n):
    index = np.where(df.columns == df['match_this_value'][i])[0].item()
    df.iloc[i, index] = df['take_this_value'][i].day 
    df.iloc[i, (index+1):] = 0

但是,由于我的数据集非常大,这需要相当长的时间。我的示例数据集的运行时间大约为70秒,因为我的整个数据集要长得多。有没有更快的方法?此外,有没有更好的方法在不遍历每行的情况下进行这种操作?在


编辑: 对不起,我应该指定索引是如何计算的。该指数通过其中np通过将dataframe的所有列(对于每一行)与一个特定列进行比较并找到匹配项。比如说:

^{pr2}$

一旦有了这个索引,我就将该列的值设置为df中另一列的值。现在整个代码如下所示:

for i in range(n):
    index = np.where(df.columns == df['match_this_value'][i])[0].item()
    df.iloc[i, index] = df['take_this_value'][i].day 
    df.iloc[i, (index+1):] = 0

Tags: columns数据方法代码indfforindex
2条回答

考虑以下方法:

import numpy as np
import pandas as pd

# dataframe size
R, C = 10_000_000, 10

# sample data
df = pd.DataFrame(
    np.random.random((R, C)),
    columns=['name', *(f'c_{idx}' for idx in range(C - 1))])

# calculating specific index
cut_column = np.random.randint(1, C, (R,))

# handling data column by column
for idx, col in enumerate(df.columns[1:], 1):
    df[col] = np.where(cut_column > idx, df[col], 0)

在我的机器上运行1000万行的时间大约是秒。在

你可以:


import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(4, 4), columns=list('ABCD'))

#           A         B         C         D
# 0  0.750017  0.582230  1.411253 -0.379428
# 1 -0.747129  1.800677 -1.243459 -0.098760
# 2 -0.742997 -0.035036  1.012052 -0.767602
# 3 -0.694679  1.013968 -1.000412  0.752191

indexes = np.random.choice(range(df.shape[1]), df.shape[0])
# array([0, 3, 1, 1])
df_indexes = np.tile(range(df.shape[1]), (df.shape[0], 1))
df[df_indexes>indexes[:, None]] = 0
print(df) 
#           A         B         C        D
# 0  0.750017  0.000000  0.000000  0.00000
# 1 -0.747129  1.800677 -1.243459 -0.09876
# 2 -0.742997 -0.035036  0.000000  0.00000
# 3 -0.694679  1.013968  0.000000  0.00000

所以这里包含一个布尔掩码df_indexes>indexes[:, None],这里的indexes将被替换为“特定索引”

相关问题 更多 >