使用Pandas3

问题描述 投票:0回答:0

I在多年前从Numpy阵列切换到Pandas DataFrames(DFS),因为后者具有列名,

iake编程更容易;
  1. 在读取
  2. .json
  3. .csv
    文件的数据时会更改。
    从不时,我需要一些
  4. [-1]
的某些列的最后一行(

col

),并将其与另一个列的同一列的最后一行结合。  我知道列的
名,而不是它们的位置/顺序(我知道,但它可能会改变,我想拥有一个与列的代码相对于变换器的代码)。
所以我多年来在许多python脚本中一直在做什么,看起来像
df1
但由于一段时间以来,我的邮箱被Cron Jobs淹没了,告诉我那个
col
当然,此错误消息是不正确的,并用我的示例中的最后一行替换了最后一行
df2

也无法工作,因为

import numpy as np import pandas as pd # In reality, these are read from json files - the order of the columns may change, their names may not: df1 = pd.DataFrame(np.random.random((2,3)), columns=['col2','col3','col1']) df2 = pd.DataFrame(np.random.random((4,3)), columns=['col1','col3','col2']) df1.col2.iloc[-1] = df2.col2.iloc[-1]

无法处理列名,并且
You are setting values through chained assignment. Currently this works in certain cases, but when using Copy-on-Write (which will become the default behaviour in pandas 3.0) this will never work to update the original DataFrame or Series, because the intermediate object on which we are setting values will behave as a copy.
A typical example is when you are setting values in a column of a DataFrame, like:

df["col"][row_indexer] = value

Use `df.loc[row_indexer, "col"] = values` instead, to perform the assignment in a single step and ensure this keeps updating the original `df`.

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

  df1.col2.iloc[-1] = df2.col2.iloc[-1]
无法处理相对数字。

如何处理带有pandas dataframe名称的最后一个(或任何其他相对号)行?

	

您可以尝试使用以下片段。

df1.loc[-1, 'col2'] = df2.loc[-1, 'col2']    # KeyError: -1
df1.iloc[-1, 'col2'] = df2.iloc[-1, 'col2']  # ValueError (can't handle 'col2')

在我的机器上使用熊猫版本

.iloc[]
没有任何警告。
	

python pandas dataframe
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.