想要修改其中一个序列
df['description'] = df['description'].str.upper().str[:30]
运行结果没问题,但总是提示
A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead
求教这个用.loc 的正确写法应该是什么呢?
1
imn1 2018-12-14 11:57:44 +08:00
用 str.slice()试试
|
2
congeec 2018-12-14 12:12:17 +08:00
df['description'] = df['description'].map(str.upper).map(lambda x: x[:30])
|
3
lance6716 2018-12-14 12:35:20 +08:00 via Android 1
df = df.copy() 然后再
|
4
youthfire OP @lance6716 感谢,特地去了解了下 df.copy().
我的例子确实写的不太好,其实是我用另一个 cf 名 copy 了原来的 df,写的是 cf['description'] = cf['description'].str.upper().str[:30],没了解 cf=df 不等于 df.copy,Stackflow 的解释更多些: Because if you don't make a copy then the indices can still be manipulated elsewhere even if you assign the dataFrame to a different name. For example: df2 = df func1(df2) func2(df) func1 can modify df by modifying df2, so to avoid that: df2 = df.copy() func1(df2) func2(df) 也谢谢所有回答者。 |