简体   繁体   English

将值设置为Pandas数据框的切片

[英]Set value to slice of a Pandas dataframe

I want to sort a subset of a dataframe (say, between indexes i and j) according to some value. 我想根据某个值对数据框的子集进行排序(例如,在索引i和j之间)。 I tried 我试过了

df2=df.iloc[i:j].sort_values(by=...)
df.iloc[i:j]=df2

No problem with the first line but nothing happens when I run the second one (not even an error). 第一行没有问题,但是运行第二行没有任何反应(甚至没有错误)。 How should I do ? 我应该怎么做 ? (I tried also the update function but it didn't do either). (我也尝试了更新功能,但没有执行任何操作)。

I believe need assign to filtered DataFrame with converting to numpy array by values for avoid align indices: 我相信需要分配给过滤后的DataFrame并通过将values转换为numpy数组来避免对齐索引:

df = pd.DataFrame({'A': [1,2,3,4,3,2,1,4,1,2]})
print (df)
   A
0  1
1  2
2  3
3  4
4  3
5  2
6  1
7  4
8  1
9  2

i = 2
j = 7
df.iloc[i:j] = df.iloc[i:j].sort_values(by='A').values
print (df)
   A
0  1
1  2
2  1
3  2
4  3
5  3
6  4
7  4
8  1
9  2

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

相关问题 Pandas DataFrame:SettingWithCopyWarning:尝试在DataFrame的切片副本上设置值 - Pandas DataFrame: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame pandas 值正在尝试在 DataFrame 的切片副本上设置 - pandas value is trying to be set on a copy of a slice from a DataFrame python pandas:尝试在DataFrame的切片副本上设置一个值 - python pandas: A value is trying to be set on a copy of a slice from a DataFrame pandas 错误:正在尝试在 DataFrame 中的切片副本上设置值 - pandas error: value is trying to be set on a copy of a slice from a DataFrame Python Pandas 警告:试图在 DataFrame 的切片副本上设置值 - Python Pandas Warning: A value is trying to be set on a copy of a slice from a DataFrame 试图在 DataFrame 的切片副本上设置一个值。- pandas - A value is trying to be set on a copy of a slice from a DataFrame. - pandas 为pandas DataFrame设置值:警告试图在DataFrame的切片副本上设置值 - Setting a value to a pandas DataFrame: Warning A value is trying to be set on a copy of a slice from a DataFrame Pandas,设置在 DataFrame 问题切片的副本上 - Pandas, set on a copy of a slice from DataFrame problem 按列中的部分字符串值对熊猫数据框进行切片 - Slice pandas dataframe by part of string value in column 熊猫数据框无法将值分配给切片子集 - pandas dataframe fails to assign value to slice subset
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM