[英]Combine Row Index and Row Value (String) For Specific Rows in Pandas DataFrame
Let's say that I have a Pandas DataFrame:假设我有一个 Pandas DataFrame:
df = pd.DataFrame({'col1': range(10), 'col2': ['a', 'b', 'c', 'a', 'e', 'f', 'g', 'a', 'h', 'i']})
and it looks like:它看起来像:
col1 col2
0 0 a
1 1 b
2 2 c
3 3 a
4 4 e
5 5 f
6 6 g
7 7 a
8 8 h
9 9 i
I want to update all values where df['col2'] == 'a'
and append the row index to a
so that we get:我想更新
df['col2'] == 'a'
所有值并将行索引附加到a
以便我们得到:
col1 col2
0 0 a_0
1 1 b
2 2 c
3 3 a_3
4 4 e
5 5 f
6 6 g
7 7 a_7
8 8 h
9 9 i
Use series.mask
with series.eq
to compare if value equals a
and add
col1/index after converting to string使用
series.mask
和series.eq
比较值是否等于a
并在转换为字符串后add
col1/index
df['col2']=df['col2'].mask(df['col2'].eq('a'),df['col2'].add('_'+df.index.astype(str)))
#df['col2']=df['col2'].mask(df['col2'].eq('a'),df['col2'].add('_'+df['col1'].astype(str)))
print(df)
col1 col2
0 0 a_0
1 1 b
2 2 c
3 3 a_3
4 4 e
5 5 f
6 6 g
7 7 a_7
8 8 h
9 9 i
df.assign(col2=[f'{v}_{i}' if v == 'a' else v for i, v in df.col2.iteritems()])
col1 col2
0 0 a_0
1 1 b
2 2 c
3 3 a_3
4 4 e
5 5 f
6 6 g
7 7 a_7
8 8 h
9 9 i
A very low memory footprint loop that edits in place一个非常低的内存占用循环,可以就地编辑
for i, v in df.col2.iteritems():
if v == 'a':
df.at[i, 'col2'] = f'a_{i}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.