Pandas怎樣新增數據列?
在進行數據分析時,經常需要按照一定條件創建新的數據列,然后進行進一步分析。
- 直接賦值
- df.apply方法
- df.assign方法
- 按條件選擇分組分別賦值
0、讀取csv數據到dataframe
1、直接賦值的方法
實例:清理溫度列,變成數字類型
實例:計算溫差
2、df.apply方法
Apply a function along an axis of the DataFrame.
Objects passed to the function are Series objects whose index is either the DataFrame’s index (axis=0) or the DataFrame’s columns (axis=1).
實例:添加一列溫度類型:
- 如果最高溫度大於33度就是高溫
- 低於-10度是低溫
- 否則是常溫
3、df.assign方法
Assign new columns to a DataFrame.
Returns a new object with all original columns in addition to new ones.
實例:將溫度從攝氏度變成華氏度
4、按條件選擇分組分別賦值
按條件先選擇數據,然后對這部分數據賦值新列
實例:高低溫差大於10度,則認為溫差大