我創建了一個串列作為其他 2 列的平均值,串列的長度與資料框中的行數相同。但是,當我嘗試將該串列作為列添加到資料框時,整個串列將被分配給每一行,而不僅僅是串列的相應值。
glucose_mean = []
for i in range(len(df)):
mean = (df['h1_glucose_max'] df['h1_glucose_min'])/2
glucose_mean.append(mean)
df['glucose'] = glucose_mean
添加串列后的資料
uj5u.com熱心網友回復:
我認為你把它復雜化了。你不需要for-loop 但只有一行
df['glucose'] = (df['h1_glucose_max'] df['h1_glucose_min']) / 2
編輯:
如果您想分別處理每一行,那么您可以使用.apply()
def func(row):
return (row['h1_glucose_max'] row['h1_glucose_min']) / 2
df['glucose'] = df.apply(func, axis=1)
如果你真的需要使用for-loop 那么你可以使用.iterrows()(或類似的功能)
glucose_mean = []
for index, row in df.iterrows():
mean = (row['h1_glucose_max'] row['h1_glucose_min']) / 2
glucose_mean.append(mean)
df['glucose'] = glucose_mean
最小的作業示例:
import pandas as pd
data = {
'h1_glucose_min': [1,2,3],
'h1_glucose_max': [4,5,6],
}
df = pd.DataFrame(data)
# - version 1 -
df['glucose_1'] = (df['h1_glucose_max'] df['h1_glucose_min']) / 2
# - version 2 -
def func(row):
return (row['h1_glucose_max'] row['h1_glucose_min']) / 2
df['glucose_2'] = df.apply(func, axis=1)
# - version 3 -
glucose_mean = []
for index, row in df.iterrows():
mean = (row['h1_glucose_max'] row['h1_glucose_min']) / 2
glucose_mean.append(mean)
df['glucose_3'] = glucose_mean
print(df)
uj5u.com熱心網友回復:
您不需要遍歷您的框架。改用它(偽資料框的示例):
df = pd.DataFrame({'col1': [1, 2, 3, 4, 5, 6, 7, 8], 'col2': [10, 9, 8, 7, 6, 5, 4, 100]})
df['mean_col1_col2'] = df[['col1', 'col2']].mean(axis=1)
df
-----------------------------------
col1 col2 mean_col1_col2
0 1 10 5.5
1 2 9 5.5
2 3 8 5.5
3 4 7 5.5
4 5 6 5.5
5 6 5 5.5
6 7 4 5.5
7 8 100 54.0
-----------------------------------
uj5u.com熱心網友回復:
正如您在以下示例中看到的那樣,每次執行 for 回圈時,您的代碼都會附加一整列,因此當您將glucose_mean串列分配為列時,每個元素都是一個串列而不是單個元素:
import pandas as pd
df = pd.DataFrame({'col1':[1, 2, 3, 4], 'col2':[2, 3, 4, 5]})
glucose_mean = []
for i in range(len(df)):
glucose_mean.append(df['col1'])
print((glucose_mean[0]))
df['col2'] = [5, 6, 7, 8]
print(df)
輸出:
0 1
1 2
2 3
3 4
Name: col1, dtype: int64
col1 col2
0 1 5
1 2 6
2 3 7
3 4 8
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/497802.html
上一篇:從多索引資料框中提取行,其中子級別與Numpy陣列上的數字匹配
下一篇:隱藏層中權重的形狀(多層感知器)
