python - 附加数据帧时修复索引
问题描述
我正在附加三个 CSV:
df = pd.read_csv("places_1.csv")
temp = pd.read_csv("places_2.csv")
df = df.append(temp)
temp = pd.read_csv("places_3.csv")
df = df.append(temp)
print(df.head(20))
连接表如下所示:
location device_count population
0 A 11 NaN
1 B 12 NaN
2 C 13 NaN
3 D 14 NaN
4 E 15 NaN
0 F 21 NaN
1 G 22 NaN
2 H 23 NaN
3 I 24 NaN
4 J 25 NaN
0 K 31 NaN
1 L 32 NaN
2 M 33 NaN
3 N 34 NaN
4 O 35 NaN
如您所见,索引不是唯一的。
当我调用这个 iloc 函数将人口列乘以 2 时:
df2 = df.copy
for index, row in df.iterrows():
df.iloc[index, df.columns.get_loc('population')] = row['device_count'] * 2
我得到以下错误结果:
location device_count population
0 A 11 62.0
1 B 12 64.0
2 C 13 66.0
3 D 14 68.0
4 E 15 70.0
0 F 21 NaN
1 G 22 NaN
2 H 23 NaN
3 I 24 NaN
4 J 25 NaN
0 K 31 NaN
1 L 32 NaN
2 M 33 NaN
3 N 34 NaN
4 O 35 NaN
对于每个 CSV,它都会覆盖第一个 CSV 的索引,我还尝试创建一个新的整数列并调用 df.set_index()。那没有用。
有小费吗?
解决方案
第一,使用ignore_index
,第二,不要使用append
,使用pd.concat([temp1, temp2, temp3], ignore_index=True)
。
推荐阅读
- javascript - 点击后直接打印
- android - 边框中的 TextInputLayout.OutlinedBox 渐变颜色
- entity-framework-5 - 运行 SqlQuery 按日期计算行数
- angularjs - 在angularjs中重定向到具有不同url名称的同一页面
- java - 为什么我的 JSON 在 Internet 上发布时会更改类型?
- dart - Flutter PaginatedDataTable rowsPerPage
- python - 具有相同列名并应用聚合函数的内部合并数据框
- reactjs - React 状态具有数组作为属性,但是当传递它时它会嵌套到一个同名对象中?
- android - public open fun get() Picasso 的争论太多了!在 com.squareup.picasso.Picasso 中定义
- jquery - Jquery ajax禁用提交按钮,直到表单完成