Python 更换一个单元格';s值(以熊猫为单位)转换为元组
这可能是一个简单的问题,但我试图寻找答案,但似乎找不到。 我有一个数据帧,我想把一些单元格的值改成元组 如果我有这个:Python 更换一个单元格';s值(以熊猫为单位)转换为元组,python,pandas,string,tuples,Python,Pandas,String,Tuples,这可能是一个简单的问题,但我试图寻找答案,但似乎找不到。 我有一个数据帧,我想把一些单元格的值改成元组 如果我有这个: Col0 Col1 Col2 3 a 6 7 b 8 我想将所有“a”值更改为元组: Col0 Col1 Col2 3 (4,5) 6 7 b 8 我试着这样做: df.loc[df["Col1"]
Col0 Col1 Col2
3 a 6
7 b 8
我想将所有“a”值更改为元组:
Col0 Col1 Col2
3 (4,5) 6
7 b 8
我试着这样做:
df.loc[df["Col1"] == "a"] = (4,5,)
但它显然不起作用。我不知道该怎么做
我该怎么做呢?也许是这样的
import pandas as pd
df = pd.DataFrame(data = {'Col0': [3,7], 'Col1': ['a', 'b'], 'Col2': [6, 8]})
df.set_value(0, 'Col1', (4, 5))
或者,如果您不知道“a”在哪里(如果我们每列有一个以上的“a0”,您可以使用循环:
import pandas as pd
import numpy as np
df = pd.DataFrame(data = {'Col0': [3,7], 'Col1': ['a', 'b'], 'Col2': [6, 8]})
# find the position of a in 'Col1'
where_a = np.where(df['Col1'] == 'a')[0]
# replace a with tuple (4, 5)
for x in where_a:
df.set_value(x, 'Col1', (4, 5))
Col0 Col1 Col2
0 3 (4, 5) 6
1 7 b 8
让我们尝试使用
loc
进行布尔索引,以更新Col1
中包含a
的单元格中的值:
m = df['Col1'].eq('a')
df.loc[m, 'Col1'] = pd.Series([(4, 5)]*m.sum(), index=m[m].index)
或者,您可以尝试将填充值参数设置为tuple(4,5)
:
成功了!非常感谢!:)
m = df['Col1'].eq('a')
df['Col1'] = df.loc[~m, 'Col1'].reindex(m.index, fill_value=(4, 5))
Col0 Col1 Col2
0 3 (4, 5) 6
1 7 b 8