繁体   English   中英

根据不同的列熊猫输入值

[英]Input values based on a different column pandas

我希望从上方的一个单元格中复制下来的值,只要另一列中的值相同,并且不使用现有值的平均值即可。

基本上,我想创建一个时间序列,应该使用之前的值,除非没有基准。

下面的示例和示例解决方案

在此处输入图片说明 在此处输入图片说明

Name Date Value
A 01/01/2018
A 02/01/2018
A 03/01/2018
A 04/01/2018 15
A 05/01/2018
A 06/01/2018 18
B 01/01/2018
B 02/01/2018
B 03/01/2018
B 04/01/2018
B 05/01/2018 30
B 06/01/2018
B 07/01/2018
B 08/01/2018 35
B 09/01/2018
B 10/01/2018
C 01/01/2018
C 02/01/2018
C 03/01/2018
C 04/01/2018 45
C 05/01/2018
C 06/01/2018
C 07/01/2018 53
C 08/01/2018
C 09/01/2018 48
C 10/01/2018
C 11/01/2018
C 12/01/2018 

您可以尝试以下

# Calculate the mean and put it to an auxiliary column
df = df.set_index('Name')
df['Mean'] = df.groupby(df.index)['Value'].mean()

# Forward fill the gaps [.ffill() doesn't work here for some reason]
df['Value'] = df.groupby(df.index)['Value'].fillna(method='ffill')

# Fill the remaining gaps with the mean
df['Value'] = df['Value'].fillna(df['Mean'])

# Remove the auxiliary column and the index
df = df.drop('Mean', 1).reset_index()

为您提供您发布的确切输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM