![](/img/trans.png)
[英]How to excute statement each time a for loop increase to a certain index in Python?
[英]How to get the value and index at the same time with 1 for loop statement
我有一個數據框,我想使用 for 循環來獲取列值和該值的索引。
下面是 dataframe 我正在嘗試從日期列中獲取值
下面是我的代碼。 我聲明了一個計數變量來跟蹤索引。 我的問題:是否有可能在 for 循環聲明中,我可以在一行中獲取列值及其索引?
此行for row in loadexpense_df["Date"]:
中的行的含義,行是包含日期列中的值的變量。 可以改進for循環以獲取值及其索引嗎?
謝謝
count =0
load = loadexpense_df["Date"]
for row in loadexpense_df["Date"]:
checkMonth = row.strftime("%m")
if checkMonth == '01':
loadexpense_df["Month"][count] = "Jul"
elif checkMonth == '02':
loadexpense_df["Month"][count] = "Aug"
elif checkMonth == '03':
loadexpense_df["Month"][count] = "Sep"
elif checkMonth == '04':
count = count +1
這是一個可以幫助你的例子。
mylist = ["ball","cat","apple"]
for idx, val in enumerate(mylist):
print ("index is {0} and value is {1}".format(idx, val))
iterrows 返回索引和該行表示為系列的行
for index, row in df.iterrows():
請參閱此處了解更多信息:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html
這就是ititems的用途:
for idx, val in loadexpense_df['Date'].items():
pass
但是,您的代碼可能在鏈索引方面存在一些問題。 例如:
loadexpense_df["Month"][count] = "Jul"
我認為您應該查看np.select
或.loc
訪問權限。 這有助於提高代碼的可讀性和性能。 例如:
checkMonth = loadexpense_df['Date'].dt.month
loadexpense_df.loc[checkMonth==1, 'month'] = 'Jul'
...
您必須考慮“熊貓方式”,並且應盡可能將循環創建留給 pandas。 一個解決方案示例:
df
Date Amount
0 2019-10-25 2
1 2019-10-26 5
2 2019-10-27 52
3 2019-10-28 93
4 2019-10-29 70
5 2019-10-30 51
6 2019-10-31 80
7 2019-11-01 61
8 2019-11-02 52
9 2019-11-03 61
m={10:'jul',11:'aug'}
# The easy way to get the month: dt.month
#df["Month"]= pd.Series.replace(df.Date.dt.month, m)
df["Month"]= df.Date.dt.month.replace(m)
Date Amount Month
0 2019-10-25 2 jul
1 2019-10-26 5 jul
2 2019-10-27 52 jul
3 2019-10-28 93 jul
4 2019-10-29 70 jul
5 2019-10-30 51 jul
6 2019-10-31 80 jul
7 2019-11-01 61 aug
8 2019-11-02 52 aug
9 2019-11-03 61 aug
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.