[英]Pandas: Create a new column in a data frame with values calculated from an already existing column, i. calculate maximum
[英]How to select multiple column from a data frame and within that i need to create two new column with existing column in the same code?
我有一個由 5 列組成的數據框。 我需要提取前 3 列,我需要從最后兩列創建兩個新列?
A 欄 B 欄 C 欄 D 欄 E
df[df[1:3]]
這會給我前三列,但從列 D & EI 只需要提取最后兩個字符。 如何在相同的代碼中提取?
從廣義上講,我看到您的數據框有 5 列。 說 ABCD E。在這個 DataFrame 中,你想添加兩個基於 D 和 E 的新列。這就是你的問題所暗示的。
df[df[['A', 'B', 'C', 'D', 'E']
x = df.D
y = df.E
df['F'] = x # or just do df.F = df.D
df['G'] = y # or df.G = df.E
您將有 F 和 G 新列“基於”(技術上等同於)您的最后兩列 D 和 E。
IIUC,這應該可以解決問題
df1= df.iloc[:,:3]
df2=df.iloc[:,3:]
a=df2.columns[:]
df2[a +'_extracted'] = df2[a].apply(lambda x: x.str[-2:])
輸入
script call_put strike animals codes
a 280 280 rat nill
a 260 260 cat fill
a 275 275 pat dill
b 280 280 mat grill
b 285 285 bat shrill
輸出df1
script call_put strike
0 a 280 280
1 a 260 260
2 a 275 275
3 b 280 280
4 b 285 285
df2
animals codes animals_extracted codes_extracted
0 rat nill at ll
1 cat fill at ll
2 pat dill at ll
3 mat grill at ll
4 bat shrill at ll
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.