如何反转 pandas 系列
How to reverse a pandas series
我有一个 pandas 系列,在我将它连接到主 DataFrame 之前必须颠倒过来。
我可以用myseries轻松翻转它= myseries.iloc[::-1]
但是当我将它附加到主 DataFrame 时,它附加了默认系列而不是翻转版本。为什么翻转的系列不留在原地?
myseries = myseries.iloc[::-1]
newdf = pd.concat([newdf, myseries], axis=1)
编辑:
所以我的猜测是索引也被翻转了,当我连接它时可能使用索引来附加系列。有没有办法翻转系列中的值但保持索引不变?我的索引从 2 开始。
拼接看索引。所以你只需要在串联之前反转你的系列的索引。请参阅以下示例:
s = pd.Series([1,2,3], name='b')
s.index = s.index[::-1]
df = pd.DataFrame({'a': list('xyz')})
pd.concat([df, s], axis=1)
发生这种情况是因为串联是基于索引的。可以先保存原索引,然后将反转序列的索引设置为等于原索引:
myseries_index = myseries.index
myseries = myseries.iloc[::-1]
myseries.index = myseries_index
为我尝试 this.works:)
myseries = myseries.iloc[:,::-1]
示例代码:
import numpy as np
import pandas as pd
dataframe = pd.DataFrame([[1, 'A', "Student"],
[2, 'B', "Tutor"],
[3, 'C', "Instructor"]])
dataframe1 = pd.DataFrame([[1, 'A', "Student"],
[2, 'B', "Tutor"],
[3, 'C', "Instructor"]])
# reversing the dataframe
print("Reversed DataFrame")
dataframe = dataframe.iloc[:,::-1]
dataframe1 = pd.concat([dataframe1,dataframe],axis=1);
print(dataframe1);
我有一个 pandas 系列,在我将它连接到主 DataFrame 之前必须颠倒过来。
我可以用myseries轻松翻转它= myseries.iloc[::-1]
但是当我将它附加到主 DataFrame 时,它附加了默认系列而不是翻转版本。为什么翻转的系列不留在原地?
myseries = myseries.iloc[::-1]
newdf = pd.concat([newdf, myseries], axis=1)
编辑: 所以我的猜测是索引也被翻转了,当我连接它时可能使用索引来附加系列。有没有办法翻转系列中的值但保持索引不变?我的索引从 2 开始。
拼接看索引。所以你只需要在串联之前反转你的系列的索引。请参阅以下示例:
s = pd.Series([1,2,3], name='b')
s.index = s.index[::-1]
df = pd.DataFrame({'a': list('xyz')})
pd.concat([df, s], axis=1)
发生这种情况是因为串联是基于索引的。可以先保存原索引,然后将反转序列的索引设置为等于原索引:
myseries_index = myseries.index
myseries = myseries.iloc[::-1]
myseries.index = myseries_index
为我尝试 this.works:)
myseries = myseries.iloc[:,::-1]
示例代码:
import numpy as np
import pandas as pd
dataframe = pd.DataFrame([[1, 'A', "Student"],
[2, 'B', "Tutor"],
[3, 'C', "Instructor"]])
dataframe1 = pd.DataFrame([[1, 'A', "Student"],
[2, 'B', "Tutor"],
[3, 'C', "Instructor"]])
# reversing the dataframe
print("Reversed DataFrame")
dataframe = dataframe.iloc[:,::-1]
dataframe1 = pd.concat([dataframe1,dataframe],axis=1);
print(dataframe1);