import pandas as pd
import numpy as np
data = np.array([['', 'Col1', 'Col2', 'Col3'],
['Row1', 1, 2, 3],
['Row2', np.nan, 5, 6],
['Row3', 7, 8, 9]
])
df = pd.DataFrame(data=data[1:, 1:],
index=data[1:,0],
columns=data[0,1:])
OutPut:
Col1 Col2 Col3
Row1 1 2 3
Row2 nan 5 6
Row3 7 8 9
我想遍历数据框并将Row2 [' Col1'](循环中的当前行)中的NaN值替换为Row1 [' Col3']中的值(循环中前一个记录的不同列)
答案 0 :(得分:2)
您可以这样做的一种方法是使用stack
,ffill
和unstack
:
df.stack(dropna=False).ffill().unstack()
输出:
Col1 Col2 Col3
Row1 1 2 3
Row2 3 5 6
Row3 7 8 9
答案 1 :(得分:0)
在替换nan
之前还有一件事需要解决:
第1名:你正在使用数组,数组不接受连接类型,这意味着你的nan不再是np.nan了,它是'nan'
df.applymap(type)
Out[1244]:
Col1 Col2 Col3
Row1 <class 'str'> <class 'str'> <class 'str'>
Row2 <class 'str'> <class 'str'> <class 'str'>
Row3 <class 'str'> <class 'str'> <class 'str'>
df=df.replace('nan',np.nan)
第二,我使用np.roll
+ combine_first
来填充nan
df.combine_first(pd.DataFrame(np.roll(np.concatenate(df.values),1).reshape(3,3),index=df.index,columns=df.columns))
Out[1240]:
Col1 Col2 Col3
Row1 1 2 3
Row2 3 5 6
Row3 7 8 9
答案 2 :(得分:0)
我为没有从我的数据集发布实际数据而道歉,所以这里是:
private void BR_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
BRcount += 30;
RBcount += 10;
BRT.Text = BRcount.ToString();
RBT.Text = RBcount.ToString();
}
else if (e.Button == MouseButtons.Right)
{
if (BRcount >=30)
BRcount -= 30;
if(RBcount >=10 && BRcount >=30)
RBcount -= 10;
BRcount -= 30; //Was missing this, (copy and paste messed up, issue still present)
BRT.Text = BRcount.ToString();
RBT.Text = RBcount.ToString();
}
}
private void RB_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
RBcount += 30;
BRcount += 10;
RBT.Text = RBcount.ToString();
BRT.Text = BRcount.ToString();
}
else if (e.Button == MouseButtons.Right)
{
if (RBcount >=30 && BRcount >=10)
RBcount -= 30;
BRcount -= 10;
RBT.Text = RBcount.ToString();
BRT.Text = BRcount.ToString();
}
我需要脚本在&#39;打开&#39; 列中找到&#39; NaN&#39> 并将其替换为<来自上一个行的&#39;最后&#39; 。(此处用双星号突出显示)。
我感谢所有的帖子,但是,这是最终的工作:
Open High Low Last Change Settle Volume
Date
2017-05-22 51.97 52.28 51.73 **51.96** 0.49 52.05 70581.0
2017-05-23 **NaN** 52.44 51.61 52.31 0.24 52.35 9003.0
2017-05-24 52.34 52.63 51.91 52.05 0.23 52.12 11678.0
2017-05-25 52.25 52.61 49.49 49.59 2.28 49.84 19721.0
2017-05-26 49.82 50.73 49.34 50.73 0.82 50.66 11214.0