我想更改数据框的第二行。
我有这样的df:
Node | Feature | Indicator | Value | Class | Direction
--------------------------------------------------------
1 | WPS | <= | 0.27 | 4 | 1 -> 2
--------------------------------------------------------
2 | ABC | <= | 0.40 | 5 | 1 -> 3
--------------------------------------------------------
3 | CXC | <= | 0.45 | 2 | 2 -> 4
--------------------------------------------------------
4 | DFT | <= | 0.56 | 1 | 2 -> 5
--------------------------------------------------------
5 | KPL | <= | 0.30 | 3 | 3 -> 5
--------------------------------------------------------
6 | ERT | <= | 0.55 | 5 | 3 -> 1
我想要以下内容:
Node | Feature | Indicator | Value | Class | Direction
--------------------------------------------------------
1 | WPS | <= | 0.27 | 4 | 1 -> 2
--------------------------------------------------------
2 | WPS | > | 0.27 | 5 | 1 -> 3
--------------------------------------------------------
3 | CXC | <= | 0.45 | 2 | 2 -> 4
--------------------------------------------------------
4 | CXC | > | 0.45 | 1 | 2 -> 5
--------------------------------------------------------
5 | KPL | <= | 0.30 | 3 | 3 -> 5
--------------------------------------------------------
6 | KPL | > | 0.30 | 5 | 3 -> 1
因此,第二行将“功能”和“值”更改为与上一行相同,并且“指标”更改为“>”
我无法弄清楚如何遍历数据框(使用我想的迭代方法)并仅更改第二行?
编辑:
我尝试了以下建议:
my_df = pd.DataFrame()
my_df['N'] = [1, 2, 3, 4, 5, 6]
my_df['I'] = ['=>', '=>', '=>', '=>', '=>', '=>']
my_df['F'] = ['a', 'b', 'c', 'd', 'e', 'f']
my_df.loc[1::2, 'F'] = None
my_df.loc[1::2, 'I'] = '>'
my_df.fillna(method='ffill')
print(my_df)
输出:
N I F
0 1 => a
1 2 > None
2 3 => c
3 4 > None
4 5 => e
5 6 > None
答案 0 :(得分:1)
下面是使用的逻辑
import pandas as pd xlsColName = chr(ord('A')+colPosn) # Get xls column name (not the column header as per data frame). This will be used to set attributes of xls columns df = pd.read_csv('temp.csv') df.loc[1::2, 'Feature'] = None # prepare the field for use with df.fillna df.loc[1::2, 'Value'] = None df.loc[1::2, 'Indicator'] = '>' # update the indicator field df.fillna(method='ffill', inplace=True) # This fills the NaN values from existing values
答案 1 :(得分:0)
您可以尝试以下方式:
df ['Indicator'] =“>”如果df ['Node']%2 == 0否则为“ <=”
这是如果“节点”列与索引相似。