【问题标题】:how to copy and paste values until specific column ends in python dataframe如何复制和粘贴值直到特定列在python数据框中结束
【发布时间】:2021-06-25 11:10:32
【问题描述】:

我正在尝试用以前的值填充 nans,所以想知道如何复制和粘贴值直到单列结束。

这是我得到的数据

Time                indicator   Value
2021-03-01 11:00     602500     1015.31
2021-05-01 8:00      602500     1017.61
2021-05-01 5:00      307001     3485.2
NaN                  307001     3335.5
NaN                  307002     3357.3
...                  ...        ...
NaN                  307005     3337.5

3045 rows * 3 columns

我想用列中以前的值填充时间中的 NaN。 我尝试使用 ffill 方法,但它只填充单个以前的值。

df['Time'].fillna(method='ffill', inplace=True)

我想用之前的所有值替换 NaN,直到列结束。

The desired output is below
Time                indicator   Value
2021-03-01 11:00     602500     1015.31
2021-05-01 8:00      602500     1017.61
2021-05-01 5:00      307001     3485.2
2021-03-01 11:00     307001     3335.5
2021-05-01 8:00      307002     3357.3
...                  ...        ...
2021-05-01 5:00      307005     3337.5

【问题讨论】:

标签: python pandas


【解决方案1】:

您可以像这样将映射传递给groupby()

df.groupby(df.index % df.Time.isna().idxmax()).ffill()

请注意,df.Time.isna().idxmax() 正在获取Time 列中第一个NaN 值的索引,以便您知道有多少值来对索引进行模数以进行分组。

【讨论】:

  • 如果我不知道我有多少个值怎么办?
  • 我得到属性错误:“numpy.ndarray”对象没有属性“idxmax”
  • 你打电话给idxmax还是idxmax()?这是一种方法而不是属性...
【解决方案2】:

您希望每次都重复相同的三个日期循环吗?最终有人可以对其进行编码,但这应该可以满足您的需求:

#! /usr/bin/env python3
##  pip3 install pandas
##  python3 -m install pandas

import pandas as pd

timestamp = pd ._libs .tslibs .timestamps .Timestamp
NaN = pd ._libs .tslibs .nattype .NaTType

'''  or you could
import numpy as np
NaN = np .nan
'''

df = pd .DataFrame( [
    [ pd .to_datetime('2021-03-01 11:00'), 602500, 1015.31 ],
    [ pd .to_datetime('2021-05-01 8:00'),  602500,  1017.61 ],
    [ pd .to_datetime('2021-05-01 5:00'),  307001,  3485.2 ],
    [ NaN,  307001,  3335.5 ],
    [ NaN,  307002,  3357.3 ],
    [ NaN,  307005,  3337.5 ],
],  columns = [ 'Time', 'Indicator', 'Value' ]  )

##  above was just for testing

for row in range( len( df .index ) ):
    entrytype = type( df .loc[ row, 'Time'] )
    if entrytype != str and entrytype != timestamp:  ##  if it's not a datetime value
        df .loc[ row, 'Time'] = df .loc[ row -3, 'Time']  ##  replace with 3 rows back

print( df )

时间指标值
0 2021-03-01 11:00:00 602500 1015.31
1 2021-05-01 08:00:00 602500 1017.61
2 2021-05-01 05:00:00 307001 3485.20
3 2021-03-01 11:00:00 307001 3335.50
4 2021-05-01 08:00:00 307002 3357.30
5 2021-05-01 05:00:00 307005 3337.50

【讨论】:

    猜你喜欢
    • 2021-03-05
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 2020-11-24
    相关资源
    最近更新 更多