将一个2列的Pandas数据框分配给一个系列,这样第一列是系列的索引,第二列是不工作的数据

46scxncf  于 2023-02-06  发布在  其他
关注(0)|答案(2)|浏览(80)

1.给定一个数据集

df = pd.DataFrame({"Runner": ["Runner1", "Runner2", "Runner3", "Runner4"], "distance":[2,1,0,1]})

1.我先去掉0。

df = df[df["Runner"] > 0]

1.我将df ["distance]指定为新Series * ser1 * 的参数 * data *,并将df [" Runner]指定为参数 * index *

ser1 = pd.Series(data=df["distance"], index=df[df["Runner"])

下面是ser1的外观-

Runner  
Runner1   NaN  
Runner2   NaN  
Runner4   NaN  
Name: distance, dtype: float64

我希望ser1显示

Runner  
Runner1    2  
Runner2    1  
Runner4    1  
Name: distance, dtype: int64
gcuhipw9

gcuhipw91#

您需要使用:

df = df[df["distance"] > 0]
ser1 = pd.Series(data=df["distance"].values, index=df["Runner"])

但理想的做法是:

ser1 = df[df["distance"] > 0].set_index('Runner')['distance']

输出:

Runner
Runner1    2
Runner2    1
Runner4    1
Name: distance, dtype: int64
ecfsfe2w

ecfsfe2w2#

要删除零,请使用

df = df[df["distance"] > 0]

那么

df['distance'].index = df['Runner']
ser1 = df['distance']
  • 输出
Runner
Runner1    2
Runner2    1
Runner4    1
Name: distance, dtype: int64

相关问题