Your dataframe has N rows and M columns. You want to join all values in each column with " + "
. All you need to do is " + ".join(df[colname])
. To get rid of the None
values, we can do df[colname].dropna()
before joining. To make sure they're strings before we join, just map the str
function on df[colname]
before joining.
So to do this for each column:
for colname in df.columns:
print(" + ".join(df[colname].dropna()) + " < 1")
Testing:
df = pd.read_csv(StringIO("0, 1, 2\nx1_3_1, x1_7_3, x1_1_4\nx1_4_1, , x1_3_4\nx1_5_1, , x1_9_4\nx1_9_1, ,"), skipinitialspace=True)
df = df.where(pd.notnull(df), None)
print(df)
# These shenanigans to mock your data
# Output:
# 0 1 2
# 0 x1_3_1 x1_7_3 x1_1_4
# 1 x1_4_1 None x1_3_4
# 2 x1_5_1 None x1_9_4
# 3 x1_9_1 None None
for colname in df.columns:
print(" + ".join(df[colname].dropna()) + " < 1")
# Output:
# x1_3_1 + x1_4_1 + x1_5_1 + x1_9_1 < 1
# x1_7_3 < 1
# x1_1_4 + x1_3_4 + x1_9_4 < 1
To write to a file, and ignore empty columns:
with open('myfile.txt', 'w') as wf:
for colname in df.columns:
col = df[colname].dropna() # Drop nones
if not col.empty: # Checking if column is not empty after dropping nones
wf.write(" + ".join(df[colname].dropna()) + " < 1\n")
We only need to open the write handle once outside the loop.