Pandas:在迭代行时有条件地将行插入到 DataFrame 中

Win*_*ags 5 python pandas

在迭代 Pandas DataFrame 中特定列的行时,如果当前迭代行中的单元格满足特定条件,我想在当前迭代行下方添加一个新行。

举例来说:

df = pd.DataFrame(data = {'A': [0.15, 0.15, 0.7], 'B': [1500, 1500, 7000]})
Run Code Online (Sandbox Code Playgroud)

数据框:

      A     B
0  0.15  1500
1  0.15  1500
2  0.70  7000
Run Code Online (Sandbox Code Playgroud)

试图:

y = 100                             #An example scalar

i = 1

for x in df['A']:
    if x is not None:               #Values in 'A' are filled atm, but not necessarily.
        df.loc[i] = [None, x*y]     #Should insert None into 'A', and product into 'B'.
        df.index = df.index + 1     #Shift index? According to this S/O answer: /sf/answers/1699927631/
    i = i + 1

df.sort_index(inplace=True)         #Sort index?
Run Code Online (Sandbox Code Playgroud)

到目前为止我还没能成功;获取不从 0 开始的移位索引编号,并且行似乎没有以有序方式插入:

      A     B
3  0.15  1500
4   NaN    70
5  0.70  7000
Run Code Online (Sandbox Code Playgroud)

我尝试了它的各种变体,尝试与 lambda 函数一起使用applymap,但无法让它工作。

期望的结果:

      A     B
0  0.15  1500
1  None  15
2  0.15  1500
3  None  15
4  0.70  7000
5  None  70
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 3

我相信你可以使用:

df = pd.DataFrame(data = {'A': [0.15, 0.15, 0.7], 
                          'B': [1500, 1500, 7000],
                          'C': [100, 200, 400]})

v = 100
L = []
for i, x in df.to_dict('index').items():
    print (x)
    #append dictionary
    L.append(x)
    #append new dictionary, for missing keys ('B, C') DataFrame constructor add NaNs 
    L.append({'A':x['A'] * v})

df = pd.DataFrame(L)
print (df)
       A       B      C
0   0.15  1500.0  100.0
1  15.00     NaN    NaN
2   0.15  1500.0  200.0
3  15.00     NaN    NaN
4   0.70  7000.0  400.0
5  70.00     NaN    NaN
Run Code Online (Sandbox Code Playgroud)