簡體   English   中英

如何在 for 循環中向 Pandas Dataframe 添加字符串值?

[英]How to add string values to Pandas Dataframe within a for loop?

我有一個df_causation數據df_causation ,我將它創建為一個帶有相應列名的空數據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.

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM