我有以下数据框df:
public void GetLastUsedID(currentId)
{
FirebaseREST.DatabaseReference reference = FirebaseREST.FirebaseDatabase.Instance.GetReference(""+currentID);
reference.GetValueAsync(10, (res) =>
{
if (res.success)
{
value = res.data.GetRawJsonValue();
Debug.Log("Success fetched data : " + value);
if(value == "")
{
continueSearch = false;
Debug.Log(currentID);
}
else
{
// recurse
GetLastID(currentId+1);
}
}
else
{
Debug.Log("Fetch data failed : " + res.message);
continueSearch = false;
}
});
}
首先,我想从索引“名称”中删除字符串“ testschip-”,以便仅在索引上获得整数。其次,对于每个唯一索引,我都希望在“长度”和“宽度”两列上应用正向填充或向后填充(无论是否需要获得NaN)。每个唯一索引都具有相同的“长度”和“宽度”。在“ testschip-3”上,我不想应用向后或向前填充。如果我向后填充“ testschip-1”(需要将前两个索引设置为2'2',那么对于索引“ testschip-1”的最后一行,我会得到一个不必要的“ 4”)。我无法事先判断是否必须事先应用向后填充或向前填充,因为我有400万行数据开始。
答案 0 :(得分:2)
使用:
df.index = df.index.str.lstrip('testschip-').astype(int)
#alternative
#df.index = df.index.str[10:].astype(int)
#df.index = df.index.str.split('-').str[-1].astype(int)
df.groupby(level = 0).apply(lambda x: x.bfill().ffill())
输出
length timestamp width
name
1 2.0 2019-08-01 00:00:00 1.0
1 2.0 2019-08-01 00:00:09 1.0
1 2.0 2019-08-01 00:00:20 1.0
1 2.0 2019-08-01 00:00:27 1.0
1 2.0 2019-08-01 00:00:38 1.0
2 4.0 2019-08-01 00:00:39 2.0
2 4.0 2019-08-01 00:00:57 2.0
2 4.0 2019-08-01 00:00:58 2.0
2 4.0 2019-08-01 00:01:17 2.0
3 NaN 2019-08-01 00:02:27 NaN
3 NaN 2019-08-01 00:03:47 NaN