简体   繁体   English

为 Pandas DataFrame 中的特定行组合行索引和行值(字符串)

[英]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.maskseries.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

Comprehension理解

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.

相关问题 给定行索引,有没有办法在 Pandas DataFrame 中组合行? - Is there a way to combine rows in a Pandas DataFrame, given the row index? 根据有条件地包含某些行特定正则表达式的行字符串值索引 pandas 数据帧 - Index a pandas dataframe based on row string value conditionally containing some row specific regex Python Pandas Dataframe 将特定日期时间行标签设置为索引中的字符串? - Python Pandas Dataframe Set specific datetime row label to string in index? 如何使用行字符串的子集在 pandas dataframe 分组中将多行组合成单行 - How to combine multiple rows into a single row in pandas dataframe grouping using a subset of the row string Pandas dataframe:特定ID的字符串值的计数 - Pandas dataframe: count number of string value is in row for specific ID 将 pandas 数据框中的所有行除以特定行 - Divide all rows in a pandas dataframe by a specific row 如何根据一行是否包含另一行中的值组合数据框中的行 - How to combine rows in dataframe based on if a row contains a value in another row 在Pandas数据框中找到索引值的行 - Find the row of an index value in a Pandas dataframe Pandas 数据框到以行索引为值的字典? - Pandas dataframe to dictionary with row index as value? 如何合并具有相同索引的多行,每一行在熊猫中只有一个真实值? - How to combine multiple rows with the same index with each row have only one true value in pandas?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM