熊猫:如何在数据框列的开头添加值

时间:2019-05-16 13:05:28

标签: python pandas

我的代码是两个循环,它们在两个不同的列中附加一个意向值。我使用带有append的函数ignore_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

有帮助吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用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