gpt4 book ai didi

python - Pandas 在数据帧的每一列的第一个有效索引之前和最后一个有效索引之后放置

转载 作者:行者123 更新时间:2023-11-30 22:12:48 24 4
gpt4 key购买 nike

我有一个像这样的数据框:

df = pd.DataFrame({'timestamp':pd.date_range('2018-01-01', '2018-01-02', freq='2h', closed='right'),'col1':[np.nan, np.nan, np.nan, 1,2,3,4,5,6,7,8,np.nan], 'col2':[np.nan, np.nan, 0, 1,2,3,4,5,np.nan,np.nan,np.nan,np.nan], 'col3':[np.nan, -1, 0, 1,2,3,4,5,6,7,8,9], 'col4':[-2, -1, 0, 1,2,3,4,np.nan,np.nan,np.nan,np.nan,np.nan]
})[['timestamp', 'col1', 'col2', 'col3', 'col4']]

看起来像这样:

             timestamp  col1  col2  col3  col4
0 2018-01-01 02:00:00 NaN NaN NaN -2.0
1 2018-01-01 04:00:00 NaN NaN -1.0 -1.0
2 2018-01-01 06:00:00 NaN 0.0 NaN 0.0
3 2018-01-01 08:00:00 1.0 1.0 1.0 1.0
4 2018-01-01 10:00:00 2.0 NaN 2.0 2.0
5 2018-01-01 12:00:00 3.0 3.0 NaN 3.0
6 2018-01-01 14:00:00 NaN 4.0 4.0 4.0
7 2018-01-01 16:00:00 5.0 NaN 5.0 NaN
8 2018-01-01 18:00:00 6.0 NaN 6.0 NaN
9 2018-01-01 20:00:00 7.0 NaN 7.0 NaN
10 2018-01-01 22:00:00 8.0 NaN 8.0 NaN
11 2018-01-02 00:00:00 NaN NaN 9.0 NaN

现在,我想找到一种高效且Python式的方法,在第一个有效索引之前和最后一个有效索引之后进行截断(对于每一列!不计算时间戳)。在本例中,我有 4 列,但实际上我有更多列,大约 600 列。我正在寻找一种方法来砍掉第一个有效索引之前的所有 NaN 值和最后一个有效索引之后的所有 NaN 值。

我猜一种方法是循环..但是有更好的方法吗?这种方式必须是高效的。我尝试使用 Melt 来“取消旋转”数据框,但这并没有帮助。

一个明显的点是,每一列在斩波后都会有不同的行数。所以我希望结果是具有时间戳和相关列的数据帧列表(每列一个)。例如:

             timestamp  col1   
3 2018-01-01 08:00:00 1.0
4 2018-01-01 10:00:00 2.0
5 2018-01-01 12:00:00 3.0
6 2018-01-01 14:00:00 NaN
7 2018-01-01 16:00:00 5.0
8 2018-01-01 18:00:00 6.0
9 2018-01-01 20:00:00 7.0
10 2018-01-01 22:00:00 8.0

我的尝试

我尝试过这样的:

final = []
columns = [c for c in df if c !='timestamp']
for col in columns:
first = df.loc[:, col].first_valid_index()
last = df.loc[:, col].last_valid_index()
final.append(df.loc[:, ['timestamp', col]].iloc[first:last+1, :])

最佳答案

一个想法是将索引设置为时间戳后使用列表或字典理解。您应该使用您的数据进行测试,看看这是否可以解决您的性能问题。如果您的限制是内存,那么它不太可能有帮助。

df = df.set_index('timestamp')

final = {col: df[col].loc[df[col].first_valid_index(): df[col].last_valid_index()] \
for col in df}

print(final)

{'col1': timestamp
2018-01-01 08:00:00 1.0
2018-01-01 10:00:00 2.0
2018-01-01 12:00:00 3.0
2018-01-01 14:00:00 4.0
2018-01-01 16:00:00 5.0
2018-01-01 18:00:00 6.0
2018-01-01 20:00:00 7.0
2018-01-01 22:00:00 8.0
Name: col1, dtype: float64,
...
'col4': timestamp
2018-01-01 02:00:00 -2.0
2018-01-01 04:00:00 -1.0
2018-01-01 06:00:00 0.0
2018-01-01 08:00:00 1.0
2018-01-01 10:00:00 2.0
2018-01-01 12:00:00 3.0
2018-01-01 14:00:00 4.0
Name: col4, dtype: float64}

关于python - Pandas 在数据帧的每一列的第一个有效索引之前和最后一个有效索引之后放置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50983646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com