python - 将某些格式奇怪的 df 行更改为列

标签 python pandas dataframe

我有一个包含数千行的数据框,此示例 df 给出了存在的不同类型的行:

df = pd.DataFrame({'col1': ['1', '2', '2', '3'],
                  'col2': ['10', '15', '20', '30'],
                    'col3': ['cat', 'dog', 'cat', 'cat'],
                   'col4': [0.2, 0.9, 'dog', 0.5],
                  'col5': [None, None, 0.3, 'dog'],
                  'col6': [None, None, None, 0.1]})

col1 , col2一切都很好。对于该行的其余部分,我想要 cat , dog , 和 catdog成为列标题。当列标题出现在一行中时,紧随其后的任何值都应该是该列中的值。

每一行的规则:

  • 如果一行只包含cat ,十进制值进入 cat列( dogcatdog 列 有None )。
  • 如果一行只包含dog ,十进制值进入 dog列( catcatdog 列有 None ).
  • 如果一行同时具有 catdog , 但只有 1 个小数,小数应该在 catdog 下以及catdog .
  • 如果一行同时具有 catdog , 但 2 个十进制数字,十进制数字位于数字前面的列下方( Nonecatdog 下方)。

例如,在第一行中,0.2直接在cat之后,所以它将进入该列(与 110 来自 col1/col2 的行)。

在第三行,0.3 , 在“cat , dog ”之后,所以 0.3进入所有列:cat , dog , 和 catdog .

期望的输出:

dfoutput = pd.DataFrame({'col1': ['1', '2', '2', '3'],
                  'col2': ['10', '15', '20', '30'],
                   'cat': [0.2, None, 0.3, 0.5],
                    'dog': [None, 0.9, 0.3, 0.1],
                    'catdog': [None, None, 0.3, None]})

最佳答案

使用np.selectnp.where:

cond1 = (df['col3']=='cat') & (df['col4']!='dog')
cond2 = (df['col3']=='cat') & (df['col4']=='dog')
cond3 = df['col3']=='dog'
cond4 = df['col5']=='dog'
cond5 = df['col4']=='dog'

df['cat'] = np.select([cond1, cond2], [df['col4'], df['col5']], None)
df['dog'] = np.select([cond3,cond4,cond5], [df['col4'], df['col6'], df['col5']], None)
df['catdog'] = np.where(cond2, df['col5'], None)

df.drop(['col3','col4','col5','col6'], axis=1, inplace=True)
print(df)

输出:

 col1 col2   cat   dog   catdog                                                                                                   
0    1   10  0.2   None  None                                                                                                   
1    2   15  None  0.9   None                                                                                                   
2    2   20  0.3   0.3   0.3                                                                                                   
3    3   30  0.5   0.1   None 

关于python - 将某些格式奇怪的 df 行更改为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54682771/

相关文章:

r - 根据多个条件筛选和提取行

python - 我不确定如何从 HTML 打印我需要的其余信息

python - 如何在对数组应用花式索引过滤器的同时将数组的一列放入新数组中?

python - "OSError: [Errno 2] No such file or directory"使用带有命令和参数的 python 子进程

Python pandas - Dataframe 使用 pd.groupby().agg() 获得第二高值

Python/Pandas : How to select a cell value, 在同一行中给出 2 个值?

python - 如何遍历 Pandas 数据框+索引中除最后一列以外的所有列?

python - 在 Pandas 中加入键不相等的地方

python - 使用 pandas 在 Excel 中应用条件格式不起作用

python - 将多个 Parquet 文件加载到数据框中进行分析