回答編集履歴
4
バグを修正
answer
CHANGED
@@ -9,7 +9,6 @@
|
|
9
9
|
for col_name, rule in rules.items():
|
10
10
|
for column in df.columns:
|
11
11
|
rule = rule.replace(column, f"df['{column}']")
|
12
|
-
rules[col_name] = rule
|
13
12
|
exec(f"new_df['{col_name}'] = {rule}")
|
14
13
|
return new_df
|
15
14
|
|
3
さらに簡素化
answer
CHANGED
@@ -3,10 +3,8 @@
|
|
3
3
|
```python
|
4
4
|
import pandas as pd
|
5
5
|
from io import StringIO
|
6
|
-
from copy import deepcopy
|
7
6
|
|
8
7
|
def create_dataframe_by_rules(df, rules):
|
9
|
-
rules = deepcopy(rules) # rulesを破壊してよいなら不要
|
10
8
|
new_df = pd.DataFrame()
|
11
9
|
for col_name, rule in rules.items():
|
12
10
|
for column in df.columns:
|
2
ループを1つにまとめた
answer
CHANGED
@@ -7,12 +7,11 @@
|
|
7
7
|
|
8
8
|
def create_dataframe_by_rules(df, rules):
|
9
9
|
rules = deepcopy(rules) # rulesを破壊してよいなら不要
|
10
|
+
new_df = pd.DataFrame()
|
10
11
|
for col_name, rule in rules.items():
|
11
12
|
for column in df.columns:
|
12
13
|
rule = rule.replace(column, f"df['{column}']")
|
13
14
|
rules[col_name] = rule
|
14
|
-
new_df = pd.DataFrame()
|
15
|
-
for col_name, rule in rules.items():
|
16
15
|
exec(f"new_df['{col_name}'] = {rule}")
|
17
16
|
return new_df
|
18
17
|
|
1
ソースコードを1つにまとめた
answer
CHANGED
@@ -1,6 +1,8 @@
|
|
1
1
|
演算子をパースするのは大変なのでexec()を使うのはどうでしょう?
|
2
2
|
|
3
3
|
```python
|
4
|
+
import pandas as pd
|
5
|
+
from io import StringIO
|
4
6
|
from copy import deepcopy
|
5
7
|
|
6
8
|
def create_dataframe_by_rules(df, rules):
|
@@ -13,11 +15,7 @@
|
|
13
15
|
for col_name, rule in rules.items():
|
14
16
|
exec(f"new_df['{col_name}'] = {rule}")
|
15
17
|
return new_df
|
16
|
-
```
|
17
18
|
|
18
|
-
```python
|
19
|
-
import pandas as pd
|
20
|
-
from io import StringIO
|
21
19
|
|
22
20
|
str_input = """
|
23
21
|
hoge,foo,bar
|