python-2.7 - 如何对数据框的行应用操作,但影响可变列?

标签 python-2.7 pandas lambda mapping boolean-operations

我有一个从 csv 读取的数据框,其中包含无关数据。 通过评估一列 SystemStart 来判断什么是无关的。 标题日期值低于该行的 SystemStart 的列中每行的任何数据都设置为 nan。例如,index = 'one' 的 SystemStart 日期为 '2016-1-5',当设置 pd.date_range 时,它​​没有要填充的 nan 值。 index= 'three' 是 '2016-1-7' 因此有两个 nan 值替换原始数据。

我可以逐行并在所有列中抛出 np.nan 值,但这很慢。有没有更快的方法?

我在下面创建了一个有代表性的数据框,我希望在没有迭代操作的情况下获得相同的结果,或者寻找一种加速这些操作的方法。任何帮助将不胜感激。

import pandas as pd
import numpy as np

start_date = '2016-1-05'
end_date = '2016-1-7'
dates = pd.date_range(start_date, end_date, freq='D')
dt_dates = pd.to_datetime(dates, unit='D')
ind = ['one', 'two', 'three']

df = pd.DataFrame(np.random.randint(0,100,size=(3, 3)), columns = dt_dates, index = ind)

df['SystemStart'] = pd.to_datetime(['2016-1-5', '2016-1-6', '2016-1-7'])

print 'Initial Dataframe: \n', df

for msn in df.index:
    zero_date_range =  pd.date_range(start_date, df.loc[msn,'SystemStart'] - pd.Timedelta(days=1), freq='D')

    # we set zeroes for all columns in the index element in question - this is a horribly slow way to do this
    df.loc[msn, zero_date_range] = np.NaN

print '\nAltered Dataframe: \n', df

下面是 df 输出,Initial 和 Altered:

Initial Dataframe: 
       2016-01-05 00:00:00  2016-01-06 00:00:00  2016-01-07 00:00:00  \
one                     24                   23                   65   
two                     21                   91                   59   
three                   62                   77                    2   

      SystemStart  
one    2016-01-05  
two    2016-01-06  
three  2016-01-07  

Altered Dataframe: 
       2016-01-05 00:00:00  2016-01-06 00:00:00  2016-01-07 00:00:00  \
one                   24.0                 23.0                   65   
two                    NaN                 91.0                   59   
three                  NaN                  NaN                    2   

      SystemStart  
one    2016-01-05  
two    2016-01-06  
three  2016-01-07  

最佳答案

我做的第一件事是确保 SystemStartdatetime

df.SystemStart = pd.to_datetime(df.SystemStart)

然后我将 SystemStart 剥离到一个单独的系列中

st = df.SystemStart

然后我从我的 df

中删除 SytstemStart
d1 = df.drop('SystemStart', 1)

然后我将剩下的列转换为 datetime

d1.columns = pd.to_datetime(d1.columns)

最后,我使用 numpy 广播来屏蔽适当的单元格,然后加入 SystemStart

d1.where(d1.columns.values >= st.values[:, None]).join(st)

enter image description here

关于python-2.7 - 如何对数据框的行应用操作,但影响可变列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41863543/

相关文章:

python - 使用 redis 和 python 进行复杂查询

c++ - 关于 C++ 代码的一些解释(lambda 包装器和可变参数模板)

python - Pandas 意外的 set_index 行为

python - 在 sklearn.cross_validation.cross_val_score 中使用 python pandas 时间戳

python - 索引 Pandas 数据帧 : integer rows, 命名列

python - tkinter 中的命令何时使用 lambda 和回调

c++ - 使用运行时常量实例化的函数模板

pandas - 按元素拆分列并使用 pandas 创建新列

postgresql - psycopg2 cursor.execute() 传入变量表名和项

python - 使用 Python 从 DataFrame 中的列溢出值