Pandas:如何在dataframe列的开头追加值

2024-05-19 02:30:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码是两个循环,在两个不同的列中附加一个序列值。我使用函数appendignore_index=True来实现,代码如下:

for index, row in df_csv_mk.iterrows():
    exp1_high= df_metrics[df_metrics.time == row['time1_high']]['absolute exposure']

    exp1_high = exp1_high.values

    if exp1_high.size == 0:
        df_exposure_mkresult=df_exposure_mkresult.append({'exp1_high': 0}, ignore_index=True)
    else:
        df_exposure_mkresult=df_exposure_mkresult.append({'exp1_high': exp1_high[0]}, ignore_index=True)

for index, row in df_csv_mk.iterrows():

    exp2_high= df_metrics[df_metrics.time == row['time2_high']]['absolute exposure']

    exp2_high = exp2_high.values

    if exp2_high.size == 0:
        df_exposure_mkresult=df_exposure_mkresult.append({'exp2_high': 0}, ignore_index=True)
    else:
        df_exposure_mkresult=df_exposure_mkresult.append({'exp2_high': exp2_high[0]}, ignore_index=True)

结果是:

exp1_high   exp2_high
0   0.000000    NaN
1   0.000000    NaN
2   0.006666    NaN
3   0.006741    NaN
4   0.006618    NaN
5   0.006617    NaN
6   0.006607    NaN
7   0.006452    NaN
8   0.006456    NaN
9   NaN 0.000000
10  NaN 0.000000
11  NaN 0.006653
12  NaN 0.006735
13  NaN 0.006617
14  NaN 0.006616
15  NaN 0.006606
16  NaN 0.006463
17  NaN 0.006442

但我想要的是:

exp1_high   exp2_high
0   0.000000    0.000000
1   0.000000    0.000000
2   0.006666    0.006653
3   0.006741    0.006735
4   0.006618    0.006617
5   0.006617    0.006616
6   0.006607    0.006606
7   0.006452    0.006463
8   0.006456    0.006442

有什么帮助吗?谢谢


Tags: 代码truedfforindexnanmetricsrow
1条回答
网友
1楼 · 发布于 2024-05-19 02:30:28

您可以使用pd.concat将序列或列合并在一起,而不是迭代每一行

例如

import pandas as pd

s1 = pd.Series(['A', 'B', 'C', 'D'])

s2 = pd.Series([1,2,3,4])

df = pd.concat([s1, s2], axis = 1)

### Outputs
    0  1
0  A  1
1  B  2
2  C  3
3  D  4

相关问题 更多 >

    热门问题