【问题标题】:Fixing Indexing when Appending Dataframes附加数据帧时修复索引
【发布时间】:2020-09-18 12:17:21
【问题描述】:

我正在附加三个 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,df.append(temp, ignore_index=True)

标签: python python-3.x pandas dataframe indexing


【解决方案1】:

第一,使用ignore_index,第二,不要使用append,使用pd.concat([temp1, temp2, temp3], ignore_index=True)

【讨论】:

  • 为什么使用 concat 而不是 append? @Igor Riven
【解决方案2】:

正如其他人所说,您可以使用ignore_index,您可能应该在这里使用pd.concat。或者,对于其他不组合 DataFrame 的情况,您也可以使用 df = df.reset_index(drop=True) 事后更改索引。

此外,出于文档here 中列出的原因,您应该避免使用iterrows()。使用以下方法效果更好:

df.loc[:, 'population'] = df.loc[:, 'device_count'].astype('int') * 2

【讨论】:

  • *2 只是我正在运行的涉及行中的多个列的更复杂函数的代理。
  • 为什么使用 concat 而不是 append?
  • @SteveScott 它更灵活,使用范围更广,因此可能更高效。 machinelearningknowledge.ai/…
  • 奇怪。 df = df.reset_index(drop=True)df.reset_index(drop=True, inplace=True) 应该可以工作...
  • 如果矢量化不是您的函数的选项,我建议您参考 cs95 对此question 的回答,以了解使用函数修改数据帧的性能分析。您会注意到 iterrows() 是您应该使用的最后一个工具
猜你喜欢
  • 2018-09-14
  • 2020-06-19
  • 1970-01-01
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 2019-08-12
  • 2023-03-25
  • 2020-08-13
相关资源
最近更新 更多