我有以下代碼。
我正在嘗試檢查numberofeachconditiononthatdate['Date']列中的“日期時間”值是否在'luckonthatdate['Date']'列中。
如果是,那么我希望將該特定的日期時間值分配給變數'value'。
如果不是,那么我希望變數“值”等于 0。
換句話說,我想為“numberofeachconditiononthatdate”資料框創建一個新的值列,指示給定日期的“運氣”試驗次數。
luckvalues = []
for idx in numberofeachconditiononthatdate.iterrows():
if numberofeachconditiononthatdate['Date'][[idx]].isin(luckonthatdate['Date']):
value = luckonthatdate['Date'][[idx]]
luckvalues = luckvalues.append(value)
else:
value = 0
luckvalues = luckvalues.append(value)
print(luckvalues)
但是,這給了我錯誤'unhashable type: 'Series''。
我將非常感謝您的幫助!
numberofeachconditiononthatdate['Date']
0 2020-04-06
1 2020-04-06
2 2020-04-06
3 2020-05-06
4 2020-05-06
5 2020-05-06
6 2020-06-06
7 2020-06-06
8 2020-06-06
9 2020-06-13
luckonthatdate['Date'].head(10)
0 2020-04-06
3 2020-05-06
6 2020-06-06
9 2020-06-13
16 2020-10-06
20 2020-11-06
23 2020-12-06
uj5u.com熱心網友回復:
您可以使用 優化它,而不是顯式的 for 回圈merge。您可以執行以下操作:
numberofeachconditiononthatdate = (numberofeachconditiononthatdate
.merge(luckonthatdate[['Date', 'luck']], how='left', on='Date'))
numberofeachconditiononthatdate['luck'] = numberofeachconditiononthatdate['luck'].fillna(0)
Dummy_Date這將在數??據框中添加一個新列numberofeachconditiononthatdate。稍后您可以根據需要重命名它。
uj5u.com熱心網友回復:
如果你想添加一個包含每個索引重復值數量的列,你應該使用value_counts()并將它傳遞給map()最后,使用fillna()。為方便起見,我將重命名:
df1 = numberofeachconditiononthatdate.copy()
df2 = luckonthatdate.copy()
然后luck使用以下方法創建列:
df2['Luck'] = df2['Date'].map(df1['Date'].value_counts()).fillna(0)
回傳:
Date Luck
0 2020-04-06 3.0
1 2020-05-06 3.0
2 2020-06-06 3.0
3 2020-06-13 1.0
4 2020-10-06 0.0
5 2020-11-06 0.0
6 2020-12-06 0.0
uj5u.com熱心網友回復:
我通過使用帶有“if string is in row”命令的 for 回圈解決了這個問題。
for i in range(0,len(numberofeachconditiononthatdate)):
if 'luck' in numberofeachconditiononthatdate['condition'].iloc[i]:
newvalue = numberofeachconditiononthatdate['numberoftrials'].iloc[i]
newvalues.append(newvalue)
else:
newvalue = 0
newvalues.append(newvalue)
print(newvalues)
[5, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 6, 0, 0]
非常感謝你的幫助 :)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/533417.html
上一篇:如何將.apply(func)與條件函式(pandas)一起使用
下一篇:Mongoosev6.2.7新的Model.save()方法不起作用在try-catch中嘗試過的承諾、回呼和異步等待沒有任何效果
