I have a column with consecutive digits in a Pandas DataFrame.
A
1
2
3
4
I would like to change all those values to a simple string, say "foo", resulting in
A
foo
foo
foo
foo
Just select the column and assign like normal:
In [194]:
df['A'] = 'foo'
df
Out[194]:
A
0 foo
1 foo
2 foo
3 foo
Assigning a scalar value will set all the rows to the same scalar value
The good answer above throws a warning. You can also do:
df.insert(0, 'A', 'foo')
where 0 is the index where the new column will be inserted.
You can also exploit the power of the .loc
property by addressing all the rows using :
as the argument. Say that your DataFrame is called df
:
df.loc[:,'A'] = 'foo'
Resulting in
A
0 foo
1 foo
2 foo
3 foo
您可以使用方法assign
:
df = df.assign(A='foo')
You could also try pd.Series.replace
:
df['A'] = df['A'].replace(df['A'], 'foo')
print(df)
Output:
A
0 foo
1 foo
2 foo
3 foo
要使其在不收到切片错误/警告的情况下工作,您可以执行以下操作:
df.loc[:]['A'] = 'foo'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.