[英]Python - how to reset the order of number in the column data frame name pandas?
[英]pandas: how could I order data frame by column name and add empty column
我的數據框看起來像這樣
df =
1324 1322 1323 1326 1327 1328 1329
278650 2.15 2.15 2.15 2.15 2.15 2.15
535947 2.15 2.15 2.15 2.15 2.15 2.15
我想像下面這樣訂購
1322 1323 1324 1326 1327 1328 1329
278650 2.15 2.15 2.15 2.15 2.15 2.15
535947 2.15 2.15 2.15 2.15 2.15 2.15
我嘗試使用pandas sort,sort_index
http://pandas.pydata.org/pandas-docs/stable/generation/pandas.DataFrame.sort.html http://pandas.pydata.org/pandas-docs/stable/generation/pandas.DataFrame.sort_index.html
但沒有弄清楚它是如何工作的
有什么有效的方法可以做到這一點嗎?
該列也缺少值
1322、1323、1324,缺失,1326、1327、1328、1329
所以我想在缺少的情況下添加空列。
在這種情況下
1322 1323 1324 1325 1326 1327 1328 1329
278650 2.15 2.15 2.15 2.15 2.15 2.15
535947 2.15 2.15 2.15 2.15 2.15 2.15
請注意,列的邊界是1322至1373。
我這樣做解決了第一個問題
weeks = range(1322,1374)
df = df.loc[:,weeks]
排序:
http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.sort.html
要添加新列:
使用原始的df1索引創建系列:
df1['e'] = Series(np.random.randn(sLength), index=df1.index)
嘗試這個:
df.sort_index(axis = 1,inplace = True) ##Sorts the DataFrame by columns (axis = 1) in place
解決排序問題,然后嘗試以下操作:
import pandas as pd
desired_cols = range(1322,1374)
for col in desired_cols:
if col not in df.columns:
df[col] = pd.Series([])
else:
pass
添加具有np.nan
值的列。
現在,由於不贊成使用sort
,
使用sort_index
:
喜歡:
df.sort_index(axis=1,inplace=True)
要么:
df=df.sort_index(axis=1)
兩種情況:
print(df)
得到想要的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.