如何以快速方式删除原始索引并设置新索引?(Python语言)

huangapple go评论63阅读模式
英文:

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[&#39;sway_diff&#39;] = df[&#39;selfLR&#39;] - np.where(df.vote.eq(0), df[&#39;ClinLR&#39;], df[&#39;DoleLR&#39;])
print(f&quot;The largest difference between a respondent&#39;s political leaning and their impression of their intended candidate&#39;s political leaning is {df.sway_diff.max()}&quot;)
num_of_diff = len(df[df[&#39;sway_diff&#39;] == 6])
print(f&quot;There&#39;re {num_of_diff} respondent(s) have that magnitude.&quot;)

#sway df
sway = df[df[&#39;sway_diff&#39;].abs() &gt;= 3]
sway = sway.reset_index()
sway.index += 1

print(f&quot;{len(sway[sway[&#39;sway_diff&#39;] &lt; 0 ])} respondents are more liebral&quot;)
print(f&quot;{len(sway[sway[&#39;sway_diff&#39;] &gt; 0 ])} repondents are more conservative&quot;)
print(f&quot;{len(sway[sway[&#39;vote&#39;] == 1])} respondents vote for Dole&quot;)
print(f&quot;{len(sway[sway[&#39;vote&#39;] == 0])} respondents vote for Clinton&quot;)

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.

如何以快速方式删除原始索引并设置新索引?(Python语言)

答案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[&#39;sway_diff&#39;].abs() &gt;= 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()

huangapple
  • 本文由 发表于 2023年3月7日 07:51:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75656861.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定