我有以下索引DataFrame命名列和行不连续的数字:
a b c d
2 0.671399 0.101208 -0.181532 0.241273
3 0.446172 -0.243316 0.051767 1.577318
5 0.614758 0.075793 -0.451460 -0.012493
我想添加一个新列,'e',到现有的数据帧,并不想改变数据帧中的任何东西(即,新列始终具有与DataFrame相同的长度)。
0 -0.335485
1 -1.166658
2 -0.385571
dtype: float64
如何将列e添加到上面的例子中?
你可以像这样通过for循环插入新列:
for label,row in your_dframe.iterrows():
your_dframe.loc[label,"new_column_length"]=len(row["any_of_column_in_your_dframe"])
示例代码如下:
import pandas as pd
data = {
"any_of_column_in_your_dframe" : ["ersingulbahar","yagiz","TS"],
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
#load data into a DataFrame object:
your_dframe = pd.DataFrame(data)
for label,row in your_dframe.iterrows():
your_dframe.loc[label,"new_column_length"]=len(row["any_of_column_in_your_dframe"])
print(your_dframe)
输出如下:
any_of_column_in_your_dframe |
calories |
duration |
new_column_length |
ersingulbahar |
420 |
50 |
13.0 |
yagiz |
380 |
40 |
5.0 |
TS |
390 |
45 |
2.0 |
你也可以这样用:
your_dframe["new_column_length"]=your_dframe["any_of_column_in_your_dframe"].apply(len)
我得到了可怕的SettingWithCopyWarning,它没有通过使用iloc语法修复。我的DataFrame是由read_sql从ODBC源创建的。根据上面low - tech的建议,以下方法对我来说是有效的:
df.insert(len(df.columns), 'e', pd.Series(np.random.randn(sLength), index=df.index))
This worked fine to insert the column at the end. I don't know if it is the most efficient, but I don't like warning messages. I think there is a better solution, but I can't find it, and I think it depends on some aspect of the index.
Note. That this only works once and will give an error message if trying to overwrite and existing column.
Note As above and from 0.16.0 assign is the best solution. See documentation http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html#pandas.DataFrame.assign
Works well for data flow type where you don't overwrite your intermediate values.
但有一点需要注意,如果你这样做了
df1['e'] = Series(np.random.randn(sLength), index=df1.index)
这实际上是df1.index上的左连接。因此,如果您希望具有外部连接效果,我的解决方案可能并不完美,即创建一个包含所有数据的索引值的数据框架,然后使用上面的代码。例如,
data = pd.DataFrame(index=all_possible_values)
df1['e'] = Series(np.random.randn(sLength), index=df1.index)
要在数据帧的给定位置(0 <= loc <=列的数量)插入一个新列,只需使用datafframe .insert:
DataFrame.insert(loc, column, value)
因此,如果你想在一个名为df的数据帧的末尾添加列e,你可以使用:
e = [-0.335485, -1.166658, -0.385571]
DataFrame.insert(loc=len(df.columns), column='e', value=e)
value可以是一个Series,一个整数(在这种情况下,所有单元格都被这个值填充),或者一个类似数组的结构
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.insert.html
为了完整起见-使用DataFrame.eval()方法的另一个解决方案:
数据:
In [44]: e
Out[44]:
0 1.225506
1 -1.033944
2 -0.498953
3 -0.373332
4 0.615030
5 -0.622436
dtype: float64
In [45]: df1
Out[45]:
a b c d
0 -0.634222 -0.103264 0.745069 0.801288
4 0.782387 -0.090279 0.757662 -0.602408
5 -0.117456 2.124496 1.057301 0.765466
7 0.767532 0.104304 -0.586850 1.051297
8 -0.103272 0.958334 1.163092 1.182315
9 -0.616254 0.296678 -0.112027 0.679112
解决方案:
In [46]: df1.eval("e = @e.values", inplace=True)
In [47]: df1
Out[47]:
a b c d e
0 -0.634222 -0.103264 0.745069 0.801288 1.225506
4 0.782387 -0.090279 0.757662 -0.602408 -1.033944
5 -0.117456 2.124496 1.057301 0.765466 -0.498953
7 0.767532 0.104304 -0.586850 1.051297 -0.373332
8 -0.103272 0.958334 1.163092 1.182315 0.615030
9 -0.616254 0.296678 -0.112027 0.679112 -0.622436
import pandas as pd
# Define a dictionary containing data
data = {'a': [0,0,0.671399,0.446172,0,0.614758],
'b': [0,0,0.101208,-0.243316,0,0.075793],
'c': [0,0,-0.181532,0.051767,0,-0.451460],
'd': [0,0,0.241273,1.577318,0,-0.012493]}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
# Declare a list that is to be converted into a column
col_e = [-0.335485,-1.166658,-0.385571,0,0,0]
df['e'] = col_e
# add column 'e'
df['e'] = col_e
# Observe the result
df