[英]How do I replace cells in a Panda dataframe column based on a condition
This post consists of two questions, touching on issues I have encountered when trying to replace elements in a Panda dataframe based on a given condition.这篇文章包含两个问题,涉及我在尝试根据给定条件替换 Panda 数据框中的元素时遇到的问题。 I am new with Pandas, so any suggestions will be most helpful.
我是 Pandas 的新手,所以任何建议都将是最有帮助的。
Consider column A in a Panda dataframe object, df:考虑 Panda 数据框对象 df 中的 A 列:
SSIC
103
1040
1054
1065
107
I want to append the integer 0 to each cell that is of length less than four.我想将整数 0 附加到长度小于 4 的每个单元格。 That is, I want to obtain:
也就是说,我想获得:
SSIC
0103
1040
1054
1065
0107
The values are of type float64.这些值属于 float64 类型。
Currently, I have used this method:目前,我使用了这种方法:
SSIC1 = df['SSIC'].astype('int64').astype(str)
for i,n in enumerate(SSIC1):
if len(SSIC1[i]) == 4:
SSIC1[i] = '0' + SSIC1[i]
df['SSIC'] = SSIC1
It works, but I wonder if it is rather long-winded.它有效,但我想知道它是否相当冗长。 Is there a more direct way to resolve this?
有没有更直接的方法来解决这个问题?
I have the following two columns in a dataframe我在数据框中有以下两列
A B
2 1
3 4
4 6
5 4
5 2
I want to replace cells in column A that take on the value 5, with the values on the same row in B.我想用 B 中同一行上的值替换 A 列中值为 5 的单元格。
I have used the where condition:我使用了 where 条件:
df['A']=df['A'].where(df['A'] == 5, df['B'], inplace=True)
But it gives me the following error:但它给了我以下错误:
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
SettingWithCopyWarning:试图在 DataFrame 中切片的副本上设置值。 Try using .loc[row_indexer,col_indexer] = value instead
尝试使用 .loc[row_indexer,col_indexer] = value 代替
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy if name == ' main ':
请参阅文档中的注意事项: http : //pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy if name == ' main ':
This warning did not occur the first time I ran it.我第一次运行它时没有出现这个警告。 Any ideas why it has popped up?
任何想法为什么它突然出现?
Use the dataframe.at[] function.使用 dataframe.at[] 函数。 That is:
那是:
df.at[row_index,column_name] = 'the desired assignment' df.at[row_index,column_name] = '所需的分配'
for example:例如:
df = pd.DataFrame(data=[['iqbal',2,88]],columns=['name','roll','marks'],index=[0])
df.at[0,'name']= 'Joy'
` `
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.