[英]How to split value column and append it into dataframe pandas?
[英]Pandas: how to append a value at the beginning of a dataframe's column
我的代碼是兩個循環,它們在兩個不同的列中附加一個意向值。 我使用帶有ignore_index=True
append
函數來執行此操作,代碼如下:
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
有什么幫助嗎? 謝謝!
不必遍歷每一行,而可以使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.