gpt4 book ai didi

python - 通过添加行以不同的增量对 Pandas DataFrame 进行插值

转载 作者:行者123 更新时间:2023-12-02 16:06:39 25 4
gpt4 key购买 nike

所以,基本上,我有一个如下所示的 DataFrame:

Initial Dataframe

任务是以 0.1 步增加“深度”(添加新行),并相应地插入“值”。

它应该是这样的:(由于尺寸原因裁剪了下半部分)

Result Dataframe

这是我写的代码草稿:

import pandas as pd
df = pd.DataFrame({'Name': ['AS', 'AS', 'AS', 'DB', 'DB', 'DB'],
'Depth': [15, 16, 17, 10, 11, 12],
'Value': [100, 200, 300, 200, 300, 400]})

df['Depth']= ... #make it here with increment 0.1
df['Value'] = df['Value'].interpolate(method=linear)
df['Name'] = ... #copy it for each empty row

df.to_csv('Interpolated values.csv')

最佳答案

这是一个解决方案,它允许您使用步长的任何变化插入值(假设步长正好落在整数之间)并且插值更灵活:

my_df_list = []
step = 0.1

for label, group in df.sort_values('Depth').groupby('Name'):

# Create a lookup dictionary for interpolation lookup
lookup_dict = {x[0]:x[1] for x in group[['Depth', 'Value']].values}

# Use np.linespace because of the strictness of start and end values
new_index = np.linspace(
start = group['Depth'].min(),
stop = group['Depth'].max(),
num = int(1/step) * np.ptp(group['Depth']) + 1
)
new_values = pd.Series(
lookup_dict.get(round(x, 1)) for x in new_index
).interpolate()

# Create a tmp df with your values
df_tmp = pd.DataFrame.from_dict({
'Name': [label] * len(new_index),
'Depth': new_index,
'Value':new_values
})
my_df_list.append(df_tmp)

# Finally, combine all dfs
df_final = pd.concat(my_df_list, ignore_index=True)
    Name    Depth   Value
0 AS 15.0 100.0
1 AS 15.1 110.0
...
19 AS 16.9 290.0
20 AS 17.0 300.0
21 DB 10.0 200.0
22 DB 10.1 210.0
...
39 DB 11.8 380.0
40 DB 11.9 390.0
41 DB 12.0 400.0

关于python - 通过添加行以不同的增量对 Pandas DataFrame 进行插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69272076/

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