我在熊猫数据框中有一个连续数字的列。
A 1 2 3 4
我想将所有这些值更改为一个简单的字符串,比如“ foo”,结果是
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 could also try pd.Series.replace:
pd.Series.replace
df['A'] = df['A'].replace(df['A'], 'foo') print(df)
Output:
A 0 foo 1 foo 2 foo 3 foo
You can use the method assign:
assign
df = df.assign(A='foo')
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:
.loc
:
df
df.loc[:,'A'] = 'foo'
Resulting in
For this to work without receiving the slice error/warning, you can do this:
df.loc[:]['A'] = 'foo'