[英]for Loop for multiplying a value of each row with a specific column from another table based on condition in Python
[英]Set Column Value Based on Calculate Condition from Each Row
我有一个空的 dataframe 作为
columns_name = list(str(i) for i in range(10))
dfa = pd.DataFrame(columns=columns_name, index=['A', 'B', 'C', 'D'])
dfa['Count'] = [10, 6, 9, 4]
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 数数 | |
---|---|---|---|---|---|---|---|---|---|---|---|
一个 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 10 |
乙 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 6 |
C | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 9 |
D | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 4 |
我想用具有max(Count) - Current(max)
差异的符号替换Nan
值。 所以,最终的结果会是这样的。
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 数数 | |
---|---|---|---|---|---|---|---|---|---|---|---|
一个 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 10 |
乙 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | - | - | - | - | 6 |
C | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | 钠 | - | 9 |
D | 钠 | 钠 | 钠 | 钠 | - | - | - | - | - | - | 4 |
我被困在
dfa.at[dfa.index, [str(col) for col in list(range(dfa['Count'].max() - dfa['Count']))]] = '-'
并得到KeyError: 'Count'
实际上,您的这部分代码dfa.at[dfa.index, [str(col) for col in list(range(dfa['Count'].max() - dfa['Count']))]] = '-'
有问题。
只需尝试创建您尝试在理解中使用的列表
list(range(dfa['Count'].max() - dfa['Count']))
它会抛出TypeError
如果您注意到,您会发现(dfa['Count'].max() - dfa['Count'])
将给出以下series
:
A 0
B 4
C 1
D 6
而且由于您试图将series
传递给python的range
function,它会抛出错误。
一种可能的解决方案可能是:
for index, cols in zip(dfa.index, [list(map(str, col)) for col in (dfa).apply(lambda x: list(range(x['Count'], dfa['Count'].max())), axis=1).values]):
dfa.loc[index, cols] = '-'
OUTPUT :
Out[315]:
0 1 2 3 4 5 6 7 8 9 Count
A NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 10
B NaN NaN NaN NaN NaN NaN - - - - 6
C NaN NaN NaN NaN NaN NaN NaN NaN NaN - 9
D NaN NaN NaN NaN - - - - - - 4
广播也是一种选择:
import pandas as pd
import numpy as np
columns_name = list(str(i) for i in range(10))
dfa = pd.DataFrame(columns=columns_name, index=['A', 'B', 'C', 'D'])
dfa['Count'] = [10, 6, 9, 4]
# Broadcast based on column index (Excluding Count)
m = (
dfa['Count'].to_numpy()[:, None] == np.arange(0, dfa.shape[1] - 1)
).cumsum(axis=1).astype(bool)
# Grab Columns To Update
non_count_columns = dfa.columns[dfa.columns != 'Count']
# Update based on mask
dfa[non_count_columns] = dfa[non_count_columns].mask(m, '-')
print(dfa)
Output:
0 1 2 3 4 5 6 7 8 9 Count
A NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 10
B NaN NaN NaN NaN NaN NaN - - - - 6
C NaN NaN NaN NaN NaN NaN NaN NaN NaN - 9
D NaN NaN NaN NaN - - - - - - 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.