简体   繁体   English

从另一个 dataframe 的某些行创建 dataframe

[英]Create a dataframe from some rows of another dataframe

Here is the DataFrame I am working with, for reference.这是我正在使用的 DataFrame,供参考。

data2 = {'col10':[1.0, 2.0, 3.0, 4.0], 'col11':[100, 200, 300, 400]}
df = pd.DataFrame(data2, index = ['a', 'b', 'c', 'd'])

I'm trying to create a new DataFrame, df2, from the last two rows of this column.我正在尝试从该列的最后两行创建一个新的 DataFrame,df2。 I'm not sure how to do this and would appreciate some tips.我不确定如何做到这一点,并希望得到一些提示。

Try this:尝试这个:

newdf=df.loc[['c','d']]

>>> print(newdf)
   col10  col11
c    3.0    300
d    4.0    400

If you want a more generic solution, for example if you don;t know the index of your last tow rows, you can use the following:如果您想要一个更通用的解决方案,例如,如果您不知道最后两行的索引,您可以使用以下内容:

newdf=df.iloc[-2:]

>>> print(newdf)
   col10  col11
c    3.0    300
d    4.0    400

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建包含另一个数据框某些行的平均值的python数据框 - How to create a python dataframe containing the mean of some rows of another dataframe 如何从DataFrame获取一些行以构建另一个DataFrame? - How to get some rows from a DataFrame to build another DataFrame? 从另一个Dataframe创建Dataframe - Create Dataframe from another Dataframe 将数据框中的列的行创建为另一个数据框中的列 - Create rows of a column in a dataframe as a column in another dataframe 如何创建一个包含另一个数据帧某些行的平均值和标准差的 python 数据帧 - How to create a python dataframe containing the mean and standard deviation of some rows of another dataframe 将行从 dataframe 复制到 pandas 中的另一个 dataframe - Copy rows from a dataframe to another dataframe in pandas 从另一个数据帧向 Pandas 数据帧添加行 - Adding rows to a Pandas dataframe from another dataframe 从 dataframe 中删除发生在另一个 dataframe 中的行 - Removing rows from dataframe that occurs in another dataframe 创建循环以从数据框中动态选择行,然后将选定的行追加到另一个数据框:df.query() - Create Loop to dynamically select rows from dataframe, then append selected rows to another dataframe: df.query() 用基于索引的另一个数据帧中的行覆盖熊猫数据帧中的某些行 - Overwrite some rows in pandas dataframe with ones from another dataframe based on index
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM