英文:
How to remove the original indexes and set new indexes in a quick way? (Python language)
问题
我的代码在这里:
df['sway_diff'] = df['selfLR'] - np.where(df.vote.eq(0), df['ClinLR'], df['DoleLR'])
print(f"受访者的政治倾向与他们对候选人的政治倾向印象之间的最大差异是 {df.sway_diff.max()}")
num_of_diff = len(df[df['sway_diff'] == 6])
print(f"有 {num_of_diff} 位受访者具有这种差异。")
# sway数据框
sway = df[df['sway_diff'].abs() >= 3]
sway = sway.reset_index(drop=True)
print(f"{len(sway[sway['sway_diff'] < 0 ])} 位受访者更加自由主义")
print(f"{len(sway[sway['sway_diff'] > 0 ])} 位受访者更加保守主义")
print(f"{len(sway[sway['vote'] == 1])} 位受访者投票给 Dole")
print(f"{len(sway[sway['vote'] == 0])} 位受访者投票给 Clinton")
数据框'sway'是从'df'中提取的新数据框,保留了以前的索引。如何删除这些索引并添加新的索引?我在下面放了一个屏幕截图,希望可以帮助。
英文:
My code is here:
df['sway_diff'] = df['selfLR'] - np.where(df.vote.eq(0), df['ClinLR'], df['DoleLR'])
print(f"The largest difference between a respondent's political leaning and their impression of their intended candidate's political leaning is {df.sway_diff.max()}")
num_of_diff = len(df[df['sway_diff'] == 6])
print(f"There're {num_of_diff} respondent(s) have that magnitude.")
#sway df
sway = df[df['sway_diff'].abs() >= 3]
sway = sway.reset_index()
sway.index += 1
print(f"{len(sway[sway['sway_diff'] < 0 ])} respondents are more liebral")
print(f"{len(sway[sway['sway_diff'] > 0 ])} repondents are more conservative")
print(f"{len(sway[sway['vote'] == 1])} respondents vote for Dole")
print(f"{len(sway[sway['vote'] == 0])} respondents vote for Clinton")
The dataFrame 'sway' is a new dataFrame extracts from the 'df' and remains the previous indexes.
How to remove those indexes and add new indexes? I put a screen capture below, hope it helps.
答案1
得分: 1
尝试这个:
sway = df[df['sway_diff'].abs() >= 3].reset_index(drop=True)
# 下面是增加索引值加1的操作。
sway.index = sway.index + 1
删除这一行 sway = sway.reset_index()
英文:
Try this:
sway = df[df['sway_diff'].abs() >= 3].reset_index(drop=True)
# below is to increase the index by 1.
sway.index = sway.index + 1
delete the line sway = sway.reset_index()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论