如何在for循环中将字符串值添加到Pandas Dataframe?

问题描述 投票:0回答:1

我有一个熊猫数据框df_causation,我已将其创建为具有相应列名称的空数据框。

df_causation = pd.DataFrame(columns=['Question'])

我有一个for循环,在该循环中,每次循环都会得到一个名为cause_str的新字符串,如下所示:-

for i in range(len(X_test)):
   cause_str = hyp.join(f_imp) #cause_str is a new string obtained for each iteration 

(忽略获取方法,我只是举了一个例子)

我想将这些新字符串(cause_str)(全部)添加到每个连续的行在我的Pandas数据帧df_causation的“问题”列中。有合适的方法吗?

编辑:预期输出

df_causation.  **Causation**
   Row 0          cause_str from i = 0 th iteration in loop
   Row 1          cause_str from i = 1 th iteration in loop etc.
python pandas dataframe bigdata data-analysis
1个回答
0
投票

IIUC正确,这应该起作用:

dfd['**Causation**'] = df['df_causation.'].apply(lambda x: f'cause str from i = {x.split(" ")[1]} th iteration in loop')                                                             

df3                                                                                                                                                                                   

  df_causation.                              **Causation**
0         Row 0  cause str from i = 0 th iteration in loop
1         Row 1  cause str from i = 1 th iteration in loop

© www.soinside.com 2019 - 2024. All rights reserved.